/**
 * Oveyo PWA V7.8.1 — Page FAQ (fix bouton WhatsApp accessible)
 * ================================================================
 * Bug v7.8 : le bouton WhatsApp en bas était caché derrière la TabBar fixée.
 *
 * Fix :
 *   - paddingBottom suffisante (110px) pour que le contenu scrollable réserve
 *     l'espace sous la TabBar (96px) + safe-area iOS
 *   - height: 100dvh pour iOS Safari (dynamic viewport)
 *   - WebkitOverflowScrolling: 'touch' pour scroll fluide iOS
 *   - overscrollBehavior: 'contain' pour empêcher le bounce
 */

const FAQPage = ({ onClose, onOpenSheet }) => {
  const { ArrowLeft, Search, ChevronDown, ChevronUp, ExternalLink, MessageCircle } = window.LucideReact || {};

  const [categories, setCategories] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [expanded, setExpanded] = React.useState(new Set());

  React.useEffect(() => {
    const load = async () => {
      try {
        const r = await fetch('/api/pwa/faq');
        if (!r.ok) {
          setError('Impossible de charger la FAQ');
          setLoading(false);
          return;
        }
        const data = await r.json();
        setCategories(data.categories || []);
      } catch (e) {
        setError('Erreur de connexion');
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  const toggleEntry = (id) => {
    const next = new Set(expanded);
    if (next.has(id)) next.delete(id); else next.add(id);
    setExpanded(next);
  };

  const normalize = (s) => (s || '').toLowerCase()
    .normalize('NFD').replace(/[\u0300-\u036f]/g, '');

  const filtered = React.useMemo(() => {
    if (!search.trim()) return categories;
    const q = normalize(search);
    return categories
      .map((cat) => ({
        ...cat,
        entries: cat.entries.filter((e) =>
          normalize(e.question).includes(q) || normalize(e.answer).includes(q)
        ),
      }))
      .filter((cat) => cat.entries.length > 0);
  }, [categories, search]);

  const totalFiltered = filtered.reduce((sum, c) => sum + c.entries.length, 0);

  const handleAction = (entry) => {
    if (entry.action_url) {
      if (entry.action_url.startsWith('http')) {
        window.open(entry.action_url, '_blank');
      } else {
        window.location.href = entry.action_url;
      }
    }
  };

  return (
    <div
      className="fixed inset-0 z-[100]"
      style={{
        background: '#F1F4F9',
        maxWidth: 480,
        margin: '0 auto',
        display: 'flex',
        flexDirection: 'column',
        height: '100dvh',
        minHeight: '-webkit-fill-available',
      }}
    >
      {/* V9.0.2 : header avec bande dégradée — cohérent avec les autres pages */}
      <div
        className="flex-shrink-0 px-4 py-3"
        style={{
          background: 'linear-gradient(115deg, #102A43 0%, #1f3a5f 55%, #F4632B 130%)',  /* V9.5.9 : dégradé bleu→orange original (request user) */
          /* V8.0.1-FAQ-SAFEAREA : max(50px, ...) garantit que le titre n'est pas sous le status bar Safari */
          paddingTop: 'max(50px, calc(env(safe-area-inset-top, 0px) + 12px))',
        }}
      >
        <div className="flex items-center gap-3">
          <button onClick={onClose} className="p-2 -ml-2" aria-label="Fermer">
            <ArrowLeft size={22} style={{ color: '#FFFFFF' }} />
          </button>
          <div className="flex-1">
            <h2 className="font-display font-bold text-base leading-tight" style={{ color: '#FFFFFF' }}>Aide & FAQ</h2>
            <p className="text-[11px]" style={{ color: 'rgba(255,255,255,0.85)' }}>Réponses aux questions courantes</p>
          </div>
        </div>

        {/* V9.0 : loupe supprimée. Input semi-transparent sur le dégradé. */}
        <div className="mt-3">
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Rechercher dans la FAQ…"
            className="w-full px-3 py-2.5 rounded-xl text-sm outline-none"
            style={{
              background: 'rgba(255,255,255,0.95)',
              border: '1px solid rgba(255,255,255,0.4)',
              color: '#102A43',
            }}
          />
        </div>
      </div>

      {/* Contenu scrollable — paddingBottom pour TabBar + safe-area */}
      <div
        className="flex-1 overflow-y-auto px-4 py-4 space-y-4"
        style={{
          minHeight: 0,
          // V7.8.1 : 110px = TabBar (96px) + marge — pour que le bouton du bas soit accessible
          paddingBottom: 'calc(env(safe-area-inset-bottom, 0) + 110px)',
          WebkitOverflowScrolling: 'touch',
          overscrollBehavior: 'contain',
        }}
      >
        {loading && (
          <div className="text-center py-10">
            <div className="text-sm text-slate">Chargement…</div>
          </div>
        )}

        {error && !loading && (
          <div className="bg-white rounded-2xl p-5 text-center" style={{ border: '1px solid #FEE2E2' }}>
            <p className="text-sm text-orange">{error}</p>
            <button
              onClick={() => window.location.reload()}
              className="mt-3 px-4 py-2 rounded-xl text-sm font-bold text-white"
              style={{ background: '#F4632B' }}
            >
              Réessayer
            </button>
          </div>
        )}

        {!loading && !error && search.trim() && totalFiltered === 0 && (
          <div className="bg-white rounded-2xl p-6 text-center">
            <div className="text-3xl mb-2">🔍</div>
            <p className="text-sm text-slate">Aucun résultat pour "{search}"</p>
            <p className="text-xs text-slate mt-2">
              Essaie d'autres mots ou contacte-nous via le bot WhatsApp.
            </p>
            <a
              href="https://wa.me/15556323711?text=Bonjour"
              target="_blank"
              rel="noopener"
              className="inline-flex items-center gap-2 mt-4 px-4 py-2 rounded-xl text-sm font-bold text-white"
              style={{ background: '#25D366' }}
            >
              <MessageCircle size={16} />
              Bot WhatsApp
            </a>
          </div>
        )}

        {!loading && !error && filtered.map((cat) => (
          <div key={cat.key} className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #EAEEF4' }}>
            <div
              className="flex items-center gap-3 px-4 py-3"
              style={{ background: '#F8FAFC', borderBottom: '1px solid #EAEEF4' }}
            >
              <div
                className="w-9 h-9 rounded-xl flex items-center justify-center text-lg flex-shrink-0"
                style={{ background: '#FEEEE3' }}
              >
                {cat.icon}
              </div>
              <h3 className="font-display font-bold text-sm text-ink">{cat.label}</h3>
              <span className="ml-auto text-[10px] text-slate">{cat.entries.length}</span>
            </div>

            <div>
              {cat.entries.map((entry, idx) => {
                const isExpanded = expanded.has(entry.id) || !!search.trim();
                return (
                  <div
                    key={entry.id}
                    className={idx < cat.entries.length - 1 ? 'border-b' : ''}
                    style={{ borderColor: '#EAEEF4' }}
                  >
                    <button
                      onClick={() => toggleEntry(entry.id)}
                      className="w-full flex items-start gap-3 px-4 py-3 text-left active:bg-bg-2"
                    >
                      <div className="flex-1 min-w-0">
                        {/* V9.0.1 : icône + texte en colonnes flex pour bon alignement multi-ligne */}
                        <div className="font-semibold text-sm text-ink leading-snug" style={{ display: 'flex', gap: 6, alignItems: 'flex-start' }}>
                          {entry.icon && (
                            <span style={{ flexShrink: 0, marginTop: 1 }}>{entry.icon}</span>
                          )}
                          <span style={{ flex: 1, minWidth: 0 }}>{entry.question}</span>
                        </div>
                      </div>
                      <div className="flex-shrink-0 mt-0.5">
                        {isExpanded
                          ? <ChevronUp size={18} className="text-slate" />
                          : <ChevronDown size={18} className="text-slate" />}
                      </div>
                    </button>

                    {isExpanded && (
                      <div className="px-4 pb-4 -mt-1">
                        <div
                          className="text-sm text-ink leading-relaxed"
                          style={{ whiteSpace: 'pre-wrap' }}
                        >
                          {entry.answer.split('**').map((part, i) =>
                            i % 2 === 0 ? part : <strong key={i}>{part}</strong>
                          )}
                        </div>

                        {entry.action_url && entry.action_label && (
                          <button
                            onClick={() => handleAction(entry)}
                            className="mt-3 inline-flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold text-white"
                            style={{
                              background: entry.action_url.includes('wa.me') ? '#25D366' : '#F4632B',
                            }}
                          >
                            {entry.action_url.includes('wa.me')
                              ? <MessageCircle size={14} />
                              : <ExternalLink size={14} />}
                            {entry.action_label}
                          </button>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
            {/* V9.5.8 — Trait dégradé en bas de chaque section FAQ (style Espace Commerçant) */}
            <div
              style={{
                height: 3,
                background: 'linear-gradient(90deg, #102A43 0%, #F4632B 50%, #FFA45B 100%)',
              }}
            />
          </div>
        ))}

        {/* CTA en bas : encore des questions ? */}
        {!loading && !error && !search.trim() && (
          <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #EAEEF4' }}>
            <div className="p-5 text-center">
              <p className="text-sm text-slate">Pas trouvé ta réponse ?</p>
              <p className="text-xs text-slate mt-1">Le bot Oveyo te répond sur WhatsApp</p>
              <a
                href="https://wa.me/15556323711?text=Bonjour"
                target="_blank"
                rel="noopener"
                className="inline-flex items-center gap-2 mt-3 px-5 py-2.5 rounded-xl text-sm font-bold text-white"
                style={{ background: '#25D366' }}
              >
                <MessageCircle size={16} />
                Discuter avec le bot
              </a>
            </div>
            {/* V9.5.8 — Trait dégradé en bas du CTA */}
            <div
              style={{
                height: 3,
                background: 'linear-gradient(90deg, #102A43 0%, #F4632B 50%, #FFA45B 100%)',
              }}
            />
          </div>
        )}
      </div>
    </div>
  );
};

window.FAQPage = FAQPage;
