// ============================================
// minhahistória v2 — extras
// ThemeCarousel · Catalog temático · Depoimentos · FAQ · FinalCTA · WhatsAppFAB
// ============================================
const { useState: useStateE, useEffect: useEffectE } = React;

const _origIcon = window.Icon;
window.Icon = ({ name, size = 18, style = {}, color = 'currentColor' }) => {
  const base = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', style };
  if (name === 'camera') return <svg {...base}><path d="M3 8h4l2-3h6l2 3h4v12H3z" /><circle cx="12" cy="13" r="4" /></svg>;
  if (name === 'quote') return <svg width={size} height={size} viewBox="0 0 24 24" fill={color} style={style}><path d="M10 11c0-3 2-6 6-7v3c-2 1-3 2-3 4h3v6H10v-6zM2 11c0-3 2-6 6-7v3c-2 1-3 2-3 4h3v6H2v-6z" /></svg>;
  if (name === 'whatsapp') return <svg width={size} height={size} viewBox="0 0 24 24" fill={color} style={style}><path d="M12 2C6.5 2 2 6.5 2 12c0 1.7.5 3.4 1.3 4.8L2 22l5.4-1.4C8.7 21.5 10.3 22 12 22c5.5 0 10-4.5 10-10S17.5 2 12 2zm4.6 13.4c-.2.6-1.2 1.1-1.7 1.2-.4 0-1 .1-1.6-.1-.4-.1-.9-.3-1.5-.6-2.6-1.1-4.3-3.7-4.5-3.9-.1-.2-1-1.4-1-2.6 0-1.3.7-1.9 1-2.2.2-.3.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.8 2c.1.2 0 .4-.1.6-.1.2-.2.3-.4.4-.1.1-.3.3-.1.6.2.3.7 1.1 1.5 1.8 1 .9 1.8 1.2 2.1 1.3.3.1.5 0 .6-.1.2-.2.7-.8.9-1 .2-.3.4-.2.6-.1.3.1 1.7.8 2 1 .3.1.5.2.6.3.1.2.1.8-.1 1.3z" /></svg>;
  return _origIcon ? <_origIcon name={name} size={size} style={style} color={color} /> : null;
};

function themeAccentVar(name) {
  switch (name) {
    case 'navy': return 'var(--navy)';
    case 'orange': return 'var(--tangerine)';
    case 'purple': return 'var(--plum)';
    case 'green': return 'var(--lime-deep)';
    case 'blue': return 'var(--navy-soft)';
    case 'pink': return 'var(--coral)';
    case 'yellow': return 'var(--sun-deep)';
    case 'red': return 'var(--cherry)';
    default: return 'var(--navy)';
  }
}

const THEME_SECTION_META = {
  fantasia: { title: 'Fantasia', subtitle: 'Castelos, magia e jornadas encantadas para imaginar sem limite.', bg: 'linear-gradient(130deg,#7B46C5 0%,#2C2E8F 100%)', glyph: 'wand' },
  aventura: { title: 'Aventura', subtitle: 'Missões cheias de coragem, descobertas e superação.', bg: 'linear-gradient(130deg,#F28C28 0%,#F55D3E 100%)', glyph: 'mountain' },
  esportes: { title: 'Esportes', subtitle: 'Espírito de equipe, disciplina e emoção em cada página.', bg: 'linear-gradient(130deg,#E45050 0%,#B42337 100%)', glyph: 'crown' },
  espaco: { title: 'Espaço', subtitle: 'Viagens intergalácticas para crianças que sonham alto.', bg: 'linear-gradient(130deg,#1C3879 0%,#0A1F59 100%)', glyph: 'rocket' },
  misterio: { title: 'Mistério', subtitle: 'Pistas e segredos para pequenos detetives curiosos.', bg: 'linear-gradient(130deg,#4D3B6F 0%,#2E224A 100%)', glyph: 'star' },
  fe: { title: 'Fé', subtitle: 'Histórias com valores, esperança e amor em família.', bg: 'linear-gradient(130deg,#D4A017 0%,#A67C00 100%)', glyph: 'moon' },
  veiculos: { title: 'Veículos', subtitle: 'Motores, velocidade e aventuras sobre rodas.', bg: 'linear-gradient(130deg,#3E9E64 0%,#1D6D44 100%)', glyph: 'ship' },
};

const ThemeCarousel = () => {
  const themeIconById = {
    fantasia: 'icone_fantasia_minha_historia.svg',
    aventura: 'icone_aventura_minha_historia.svg',
    esportes: 'icone_esportes_minha_historia.svg',
    espaco: 'icone_espaco_minha_historia.svg',
    misterio: 'icone_misterio_minha_historia.svg',
    fe: 'icone_fe_minha_historia.svg',
    veiculos: 'icone_veiculos_minha_historia.svg',
  };
  const themes = (window.THEMES || []).filter((t) => themeIconById[t.id]);
  const [active, setActive] = useStateE(window.THEMES?.[0]?.id || 'fantasia');

  return (
    <section id="catalogo" className="container-x" style={{ paddingTop: 46 }}>
      <div className="section-title"><h2>Explore por <span style={{ color: 'var(--tangerine)' }}>tema</span></h2></div>
      <div className="themes-grid" style={{ display: 'grid', gridTemplateColumns: `repeat(${themes.length || 7}, 1fr)`, gap: 12, justifyItems: 'center' }}>
        {themes.map((t) => {
          const accent = themeAccentVar(t.accent);
          const count = window.STORIES.filter((s) => s.theme === t.id).length;
          const isActive = active === t.id;
          return (
            <button
              key={t.id}
              aria-label={`Tema ${t.label.replace(' / Bíblicos', '')}`}
              onClick={() => {
                setActive(t.id);
                window.__landing2ScrollToId(`tema-${t.id}`);
              }}
              style={{ textAlign: 'center', background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit', opacity: isActive ? 1 : 0.92 }}
            >
              <div className="avatar-ring" style={{ width: 110, height: 110, background: `conic-gradient(from 200deg, ${accent}, var(--sun), ${accent})`, boxShadow: isActive ? '0 0 0 4px rgba(255,122,58,0.25)' : 'none' }}>
                <div className="avatar-inner" style={{ background: accent }}>
                  <img
                    src={`/landing2/${themeIconById[t.id]}`}
                    alt={`Ícone do tema ${t.label}`}
                    loading="lazy"
                    style={{ width: '64%', height: '64%', objectFit: 'contain', display: 'block' }}
                  />
                </div>
              </div>
              <div className="font-display" style={{ marginTop: 12, fontWeight: 800, fontSize: 15, color: 'var(--navy)' }}>{t.label}</div>
              <div style={{ fontSize: 11, color: 'var(--soft)', marginTop: 2, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase' }}>{count} histórias</div>
            </button>
          );
        })}
      </div>
    </section>
  );
};

const ProductCard = ({ story }) => {
  const meta = window.THEME_CTA[story.theme] || { solid: 'purple', label: '' };
  const tintMap = {
    aventura: 'var(--tangerine-soft)', fantasia: 'var(--plum-soft)', espaco: '#E2E8F4',
    mistero: '#e9e2f8', fe: '#fff2cc', veiculos: '#e5f7ea', esportes: '#ffe4ea',
  };

  const aboutHref = story.v2Slug
    ? `/v2/historias/${story.v2Slug}`
    : (story.storyId ? `/v2/historias/${story.storyId.replace(/^story-/, '')}` : '/stories');
  const personalizeHref = story.personalizeUrl || (story.storyId ? `/stories/${story.storyId}/new` : '/stories');

  return (
    <article className="pcard" style={{ maxWidth: 330, width: '100%' }}>
      <div style={{ position: 'absolute', top: 12, right: 12, zIndex: 3, background: 'rgba(255,255,255,0.92)', color: 'var(--navy)', fontSize: 10, fontWeight: 800, letterSpacing: '0.04em', padding: '5px 10px', borderRadius: 999, textTransform: 'uppercase' }}>{meta.label}</div>
      <div className="pcard-cover" style={{ background: `linear-gradient(155deg, ${tintMap[story.theme] || 'var(--paper)'} 0%, var(--paper) 100%)` }}>
        <div className="book-art" style={{ filter: 'drop-shadow(0 16px 30px rgba(15,15,35,0.25))' }}><BookCover product={story} /></div>
      </div>
      <div className="pcard-body">
        <div className="pcard-brand" style={{ color: themeAccentVar(meta.solid) }}>{meta.label}</div>
        <h3 className="pcard-title">{story.title}</h3>
        <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 700, display: 'inline-flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <span>5–11 anos</span><span style={{ width: 3, height: 3, borderRadius: 99, background: 'var(--soft)' }} /><span>20 páginas</span><span style={{ width: 3, height: 3, borderRadius: 99, background: 'var(--soft)' }} /><span>Capa dura</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 10 }}><span className="font-display" style={{ fontSize: 22, fontWeight: 900, color: 'var(--navy)' }}>R$ 29,90</span></div>
        <div className="pcard-actions" style={{ marginTop: 12 }}>
          <a
            className="btn btn-outline"
            href={aboutHref}
            style={{ width: '100%', padding: '11px 14px', fontSize: 12, textAlign: 'center' }}
            aria-label={`Sobre o livro ${story.title}`}
          >
            Sobre o livro
          </a>
          <a
            className={`btn btn-solid-${meta.solid}`}
            href={personalizeHref}
            style={{ width: '100%', padding: '12px 14px', fontSize: 12, textAlign: 'center', color: meta.solid === 'yellow' ? 'var(--navy-darker)' : 'white' }}
            aria-label={`Personalize agora ${story.title}`}
          >
            <Icon name="sparkle" size={13} /> Personalize agora
          </a>
        </div>
      </div>
    </article>
  );
};

const ThemedBanner = ({ theme }) => {
  const meta = THEME_SECTION_META[theme];
  if (!meta) return null;
  return (
    <div id={`tema-${theme}`} style={{ borderRadius: 20, background: meta.bg, color: 'white', padding: '18px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, marginBottom: 10 }}>
      <div>
        <div style={{ fontSize: 11, letterSpacing: '0.15em', fontWeight: 900, textTransform: 'uppercase', opacity: 0.85 }}>Tema oficial</div>
        <h3 className="font-display" style={{ fontSize: 30, margin: '6px 0 4px', lineHeight: 1.05 }}>{meta.title}</h3>
        <p style={{ margin: 0, fontSize: 14, color: 'rgba(255,255,255,0.88)' }}>{meta.subtitle}</p>
      </div>
      <div style={{ width: 54, opacity: 0.7 }}><Glyph name={meta.glyph} color="white" /></div>
    </div>
  );
};

const Catalog = () => {
  const [query, setQuery] = useStateE("");

  useEffectE(() => {
    function onSearchChange(ev) {
      setQuery((ev?.detail?.query || "").toString());
    }
    window.addEventListener("landing2:search-change", onSearchChange);
    return () => window.removeEventListener("landing2:search-change", onSearchChange);
  }, []);

  function norm(v) {
    return (v || "")
      .toString()
      .normalize("NFD")
      .replace(/[\u0300-\u036f]/g, "")
      .toLowerCase()
      .trim();
  }

  const themesOrder = ['fantasia', 'aventura', 'esportes', 'espaco', 'misterio', 'fe', 'veiculos'];
  const queryN = norm(query);
  const grouped = themesOrder
    .map((theme) => {
      const themeLabel = (window.THEMES.find((t) => t.id === theme)?.label || theme).toString();
      const stories = window.STORIES.filter((s) => s.theme === theme).filter((s) => {
        if (!queryN) return true;
        const hay = norm(`${s.title} ${s.desc || ""} ${themeLabel} ${s.theme}`);
        return hay.includes(queryN);
      });
      return { theme, stories };
    })
    .filter((g) => g.stories.length > 0);

  return (
    <section className="container-x" style={{ paddingTop: 46 }}>
      <div className="section-title">
        <h2>Histórias por <span className="count">tema</span></h2>
        {queryN ? <button className="chip" aria-label={`Busca ativa: ${query}`}>Busca: {query}</button> : null}
      </div>
      <div style={{ display: 'grid', gap: 22 }}>
        {grouped.map((g) => (
          <section key={g.theme}>
            <ThemedBanner theme={g.theme} />
            <div className="catalog-grid" style={{ display: 'flex', flexWrap: 'wrap', gap: 18, justifyContent: 'flex-start' }}>
              {g.stories.map((s) => <ProductCard key={s.id} story={s} />)}
            </div>
          </section>
        ))}
        {queryN && grouped.length === 0 ? (
          <div style={{ background: "white", border: "1px solid var(--line)", borderRadius: 16, padding: "20px 18px", color: "var(--muted)", fontWeight: 700 }}>
            Nenhuma história encontrada para “{query}”. Tente outro termo.
          </div>
        ) : null}
      </div>
    </section>
  );
};

const Testimonials = () => {
  const [idx, setIdx] = useStateE(0);
  const total = window.TESTIMONIALS.length;
  const visible = 3;
  const items = Array.from({ length: visible }, (_, i) => window.TESTIMONIALS[(idx + i) % total]);

  return (
    <section style={{ marginTop: 64, paddingTop: 52, paddingBottom: 56, background: 'linear-gradient(180deg, var(--bg) 0%, var(--teal-soft) 100%)' }}>
      <div className="container-x" style={{ position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 28, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 12, fontWeight: 900, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--tangerine-deep)' }}>
              <span>★★★★★</span><span>4.9/5 · +2.800 famílias</span>
            </div>
            <h2 className="font-display" style={{ fontSize: 34, fontWeight: 900, color: 'var(--navy)', margin: '10px 0 4px' }}>Depoimentos que viraram <span style={{ color: 'var(--coral)' }}>recompra</span></h2>
            <p style={{ fontSize: 15, color: 'var(--muted)', margin: 0, maxWidth: 540 }}>Relatos reais de emoção, indicação e famílias que já pediram de novo.</p>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button aria-label="Anterior" onClick={() => setIdx((idx - 1 + total) % total)} style={navBtn(false)}><Icon name="chevron-left" /></button>
            <button aria-label="Próximo" onClick={() => setIdx((idx + 1) % total)} style={navBtn(true)}><Icon name="chevron-right" /></button>
          </div>
        </div>

        <div className="testimonials-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
          {items.map((t, i) => <TestimonialCard key={`${t.name}-${i}`} t={t} />)}
        </div>
      </div>
    </section>
  );
};

const TestimonialCard = ({ t }) => (
  <article style={{ background: 'white', borderRadius: 18, border: '1px solid var(--line)', padding: 14, boxShadow: 'var(--shadow-card)', minHeight: 302, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
    {t.type === 'video' ? (
      <div style={{ aspectRatio: '16 / 10', borderRadius: 12, overflow: 'hidden', background: '#000' }}>
        <iframe
          src={`https://www.youtube-nocookie.com/embed/${t.videoId}?rel=0`}
          title="Depoimento em vídeo"
          loading="lazy"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          allowFullScreen
          style={{ width: '100%', height: '100%', border: 'none' }}
        />
      </div>
    ) : null}

    {t.type === 'text' ? (
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'var(--tangerine-soft)', color: 'var(--tangerine-deep)', borderRadius: 999, padding: '4px 9px', fontSize: 10, fontWeight: 900, textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 2 }}>
        destaque real
      </div>
    ) : null}
    <p className="font-display" style={{ fontSize: 16, lineHeight: 1.35, color: 'var(--navy)', margin: '8px 2px 7px', fontStyle: 'italic' }}>“{t.text}”</p>
    {t.translation ? <p style={{ fontSize: 12, lineHeight: 1.45, color: 'var(--muted)', margin: '0 2px 8px', fontWeight: 600 }}>Tradução: “{t.translation}”</p> : null}
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
      <div><div style={{ fontWeight: 900, color: 'var(--navy)' }}>{t.name}</div><div style={{ fontSize: 12, color: 'var(--muted)' }}>{t.role}</div></div>
      <span style={{ background: 'var(--lime-soft)', color: 'var(--lime-deep)', fontSize: 10, fontWeight: 900, padding: '4px 8px', borderRadius: 999, textTransform: 'uppercase' }}>verificada</span>
    </div>
  </article>
);

const navBtn = (active) => ({ width: 44, height: 44, borderRadius: '50%', background: active ? 'var(--tangerine)' : 'var(--paper)', border: active ? 'none' : '1.5px solid var(--line)', color: active ? 'white' : 'var(--ink)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' });

const FAQItem = ({ q, a }) => {
  const [open, setOpen] = useStateE(false);
  return (
    <div style={{ background: 'var(--paper)', border: '1.5px solid ' + (open ? 'var(--tangerine)' : 'var(--line)'), borderRadius: 14, overflow: 'hidden' }}>
      <button onClick={() => setOpen((o) => !o)} aria-expanded={open} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '18px 20px', background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: "'Fredoka', sans-serif", fontWeight: 700, fontSize: 16, color: 'var(--navy)', textAlign: 'left', gap: 16 }}>
        <span>{q}</span><span style={{ width: 30, height: 30, borderRadius: '50%', background: open ? 'var(--tangerine)' : 'var(--tangerine-soft)', color: open ? 'white' : 'var(--tangerine-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 900 }}>+</span>
      </button>
      {open ? <div style={{ padding: '0 20px 20px', fontSize: 14.5, lineHeight: 1.6, color: 'var(--muted)', fontWeight: 500 }}>{a}</div> : null}
    </div>
  );
};

const FAQ = () => (
  <section className="container-x" style={{ paddingTop: 64 }}>
    <div style={{ textAlign: 'center', marginBottom: 36 }}>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 12, fontWeight: 900, letterSpacing: '0.16em', color: 'var(--tangerine-deep)', textTransform: 'uppercase' }}><Icon name="help" size={13} /> Perguntas frequentes</div>
      <h2 className="font-display" style={{ fontSize: 34, fontWeight: 900, color: 'var(--navy)', margin: '10px auto 6px' }}>Tire suas dúvidas antes de criar</h2>
      <p style={{ fontSize: 15, color: 'var(--muted)', margin: '0 auto', maxWidth: 560 }}>Se faltar alguma informação, nosso atendimento humano está disponível no WhatsApp.</p>
    </div>

    <div className="faq-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, maxWidth: 1080, margin: '0 auto' }}>
      {window.FAQS.map((f, i) => <FAQItem key={i} {...f} />)}
    </div>
  </section>
);

const FinalCTA = () => (
  <section className="container-x" style={{ paddingTop: 64 }}>
    <div className="final-cta" style={{ borderRadius: 28, background: 'linear-gradient(135deg, var(--navy-darker) 0%, var(--navy) 50%, var(--tangerine-deep) 130%)', color: 'white', padding: '64px 56px', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'relative', textAlign: 'center', maxWidth: 720, margin: '0 auto' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'rgba(255,255,255,0.14)', border: '1px solid rgba(255,255,255,0.28)', padding: '6px 14px', borderRadius: 999, fontSize: 11, fontWeight: 900, letterSpacing: '0.14em', textTransform: 'uppercase' }}><Icon name="sparkle" size={12} color="var(--sun)" /> Sua criança protagonista</span>
        <h2 className="font-display" style={{ fontSize: 48, fontWeight: 900, lineHeight: 1.05, margin: '20px 0 14px' }}>Crie uma memória que dura <span style={{ color: 'var(--sun)' }}>pra sempre</span>.</h2>
        <p style={{ fontSize: 17, lineHeight: 1.55, color: 'rgba(255,255,255,0.85)', margin: '0 auto', maxWidth: 560 }}>Livro infantil personalizado com acabamento premium e entrega para todo o Brasil.</p>
        <button className="btn btn-solid-orange btn-lg btn-pulse" style={{ marginTop: 28 }} onClick={() => { window.__landing2ScrollToId("catalogo"); }}><Icon name="sparkle" size={15} /> Criar meu livro agora</button>
        <div style={{ marginTop: 26, display: 'flex', justifyContent: 'center', gap: 22, flexWrap: 'wrap', fontSize: 12, color: 'rgba(255,255,255,0.82)', fontWeight: 800, letterSpacing: '0.05em', textTransform: 'uppercase' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="heart" size={14} color="var(--sun)" /> +2.800 famílias atendidas</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="book" size={14} color="var(--sun)" /> Livro personalizado</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="truck" size={14} color="var(--sun)" /> Entrega para todo o Brasil</span>
        </div>
      </div>
    </div>
  </section>
);

const WhatsAppFAB = () => (
  <a href="https://wa.me/5511999999999" target="_blank" rel="noopener noreferrer" aria-label="WhatsApp" style={{ position: 'fixed', right: 22, bottom: 22, zIndex: 60, background: 'var(--lime-deep)', color: 'white', width: 60, height: 60, borderRadius: '50%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 12px 28px rgba(130,184,61,.45)', cursor: 'pointer', textDecoration: 'none' }}>
    <Icon name="whatsapp" size={28} color="white" />
  </a>
);

Object.assign(window, { ThemeCarousel, ProductCard, Catalog, Testimonials, FAQ, FinalCTA, WhatsAppFAB });
