/* global React */
const PS = window.FlavioCorretoraDesignSystem_9d5869;
const PD = window.FCS_DATA;
const P = window.FCS;
const { Button, Icon, Card, Field, Input, Select, Textarea, Checkbox, Accordion, Alert, Badge, Tag } = PS;

const params = new URLSearchParams(location.search);
const prod = PD.productBySlug(params.get('p')) || PD.PRODUCTS[0];

function ProdForm() {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  function sendEmail() {
    const g = (id) => ((document.getElementById(id) || {}).value || '').trim();
    const fields = { Modalidade: prod.title };
    (prod.fields || []).forEach((f) => { const v = g(f.id); if (v) fields[f.label] = v; });
    if (g('p-nome')) fields['Nome'] = g('p-nome');
    if (g('p-wpp')) fields['WhatsApp'] = g('p-wpp');
    setSending(true);
    const subject = 'Cotação ' + prod.title + (fields['Nome'] ? ' — ' + fields['Nome'] : '') + ' [' + new Date().toLocaleString('pt-BR') + ']';
    return P.sendQuoteEmail(subject, fields)
      .catch(() => {
        const body = Object.entries(fields).map(([k, v]) => k + ': ' + v).join('\n');
        window.open('mailto:' + (PD.CONTACT.emailQuote || PD.CONTACT.email) + '?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body), '_blank');
      })
      .finally(() => setSending(false));
  }
  return (
    <div style={{ ...P.glassStyle, padding: 28 }}>
      {sent ? (
        <Alert tone="success" title="Solicitação enviada">Recebemos os seus dados por e-mail. Um consultor retorna com as melhores opções de {prod.title.toLowerCase()} em até 1 dia útil.</Alert>
      ) : (
        <form onSubmit={(e) => { e.preventDefault(); sendEmail().then(() => setSent(true)); }} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <h3 style={{ margin: '0 0 4px', fontSize: 'var(--fs-h4)', fontWeight: 500 }}>Cotação de {prod.title}</h3>
            <p style={{ margin: 0, fontSize: 'var(--fs-sm)', color: 'var(--text-muted)' }}>Preencha os dados do ramo, retornamos rápido.</p>
          </div>
          {prod.fields.map((f) => (
            <Field key={f.id} label={f.label} htmlFor={f.id}>
              {f.select
                ? <Select id={f.id}>{f.select.map((o) => <option key={o}>{o}</option>)}</Select>
                : <Input id={f.id} placeholder={f.ph} />}
            </Field>
          ))}
          <div style={{ height: 1, background: 'var(--border-subtle)', margin: '2px 0' }} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="fcs-2col">
            <Field label="Nome" htmlFor="p-nome"><Input id="p-nome" placeholder="Seu nome" required /></Field>
            <Field label="WhatsApp" htmlFor="p-wpp"><Input id="p-wpp" icon="phone" placeholder="(31) 90000-0000" /></Field>
          </div>
          <Checkbox label="Concordo em ser contatado e com a Política de Privacidade (LGPD)." defaultChecked />
          <Button type="submit" size="lg" fullWidth disabled={sending} iconTrailing="arrow-right">{sending ? 'Enviando...' : 'Solicitar cotação'}</Button>
          <p style={{ margin: 0, fontSize: 'var(--fs-xs)', color: 'var(--text-muted)', textAlign: 'center' }}>Seus dados são tratados conforme a LGPD e usados apenas para a cotação.</p>
        </form>
      )}
    </div>
  );
}

const related = (prod.related || []).map((s) => PD.productBySlug(s)).filter(Boolean);

/* Monta apenas em contexto standalone (não dentro do _ds_bundle.js). */
if (typeof __ds_ns === 'undefined')
P.mount(() => (
  <React.Fragment>
    {/* HERO de benefício */}
    <section style={{ background: 'var(--surface-inverse)', position: 'relative', overflow: 'hidden', marginTop: 'calc(-1 * var(--header-h))' }}>
      <P.Blobs tone="dark" />
      <div style={{ ...P.wrap, position: 'relative', paddingTop: 'calc(var(--header-h) + 2rem)', paddingBottom: 'clamp(3rem, 2rem + 4vw, 5rem)', display: 'grid', gridTemplateColumns: '1.05fr 0.95fr', gap: 48, alignItems: 'center' }} className="fcs-hero-grid">
        <P.HeroCrumbs items={[{ label: 'Início', href: 'index.html' }, { label: 'Seguros', href: 'seguros.html' }, { label: prod.title }]} style={{ gridColumn: '1 / -1' }} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
          <P.Eyebrow tone="dark">{prod.catLabel}</P.Eyebrow>
          <h1 style={{ margin: 0, fontSize: 'var(--fs-display-2)', fontWeight: 300, color: 'var(--neutral-0)', lineHeight: 1.06, letterSpacing: 'var(--ls-tight)' }}>{prod.title}</h1>
          <p style={{ margin: 0, fontFamily: 'var(--font-serif)', fontSize: 'var(--fs-h3)', fontWeight: 300, fontStyle: 'normal', color: 'var(--gold-300)' }}>{prod.tagline}</p>
          <p style={{ margin: 0, fontSize: 'var(--fs-lead)', color: 'var(--blue-200)', maxWidth: '50ch', lineHeight: 'var(--lh-relaxed)' }}>{prod.intro}</p>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Button size="lg" href={'orcamento.html?p=' + prod.slug} iconTrailing="arrow-right">Solicitar cotação</Button>
            <Button size="lg" variant="inverse" href="#" onClick={(e) => { e.preventDefault(); P.openWhats(e); }}><P.WhatsIcon size={20} color="#1EA952" />Falar no WhatsApp</Button>
          </div>
        </div>
        <div style={{ position: 'relative' }}>
          <P.Photo src={prod.photo || '../../assets/fotos/apolice.png'} alt={prod.title} ratio="4 / 3" />
          <div style={{ ...P.glassStyle, background: 'rgba(12,28,52,0.62)', border: '1px solid rgba(255,255,255,0.2)', backdropFilter: 'blur(10px)', padding: 26, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, textAlign: 'center', position: 'relative', margin: '-64px 20px 0', zIndex: 1 }}>
            <p style={{ margin: 0, fontFamily: 'var(--font-serif)', fontWeight: 300, fontSize: 'var(--fs-h3)', color: 'var(--neutral-0)' }}>{prod.one}</p>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'center', marginTop: 4 }}>
              {prod.covers.slice(0, 3).map((c) => <span key={c.t} style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-xs)', color: 'var(--blue-200)', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 'var(--radius-pill)', padding: '6px 12px' }}>{c.t}</span>)}
            </div>
          </div>
        </div>
      </div>
    </section>

    {/* ENTENDA A COBERTURA */}
    {PD.EXPLAINERS && PD.EXPLAINERS[prod.slug] && (
      <section style={{ ...P.sectionPad }}>
        <div style={P.wrap}>
          <div style={{ maxWidth: 780 }}>
            <P.Eyebrow>Entenda a cobertura</P.Eyebrow>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20, marginTop: 20 }}>
              {PD.EXPLAINERS[prod.slug].map((para, i) => (
                <p key={i} style={{ margin: 0, fontFamily: 'var(--font-serif)', fontWeight: 300, fontSize: i === 0 ? 'var(--fs-h3)' : 'var(--fs-lead)', color: i === 0 ? 'var(--text-strong)' : 'var(--text-body)', lineHeight: 1.5 }}>{para}</p>
              ))}
            </div>
          </div>
        </div>
      </section>
    )}

    {/* PARA QUEM É */}
    <section style={{ ...P.sectionPad }}>
      <div style={{ ...P.wrap }}>
        <P.SectionHead eyebrow="Para quem é" title="Feito para o seu momento" max="46ch" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }} className="fcs-seg-grid-3">
          {prod.forWhom.map((w, i) => (
            <P.Reveal key={i} delay={i * 60}>
              <Card padding="26px 24px" style={{ display: 'flex', gap: 14, alignItems: 'flex-start', height: '100%' }}>
                <Icon name="check-circle-2" size={22} color="var(--blue-600)" strokeWidth={1.75} style={{ flex: '0 0 auto', marginTop: 2 }} />
                <p style={{ margin: 0, color: 'var(--text-body)', lineHeight: 'var(--lh-relaxed)' }}>{w}</p>
              </Card>
            </P.Reveal>
          ))}
        </div>
      </div>
    </section>

    {/* O QUE COBRE */}
    <section style={{ ...P.sectionPad, background: 'var(--surface-subtle)' }}>
      <div style={P.wrap}>
        <P.SectionHead eyebrow="O que cobre" title="Coberturas em linguagem simples" intro="Sem juridiquês: o que está protegido e por quê." max="48ch" />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }} className="fcs-seg-grid-3">
          {prod.covers.map((c, i) => (
            <P.Reveal key={i}>
              <Card padding="24px 26px" style={{ display: 'flex', gap: 16, alignItems: 'flex-start', height: '100%' }}>
                <span style={{ width: 44, height: 44, flex: '0 0 auto', borderRadius: 'var(--radius-md)', background: 'var(--blue-50)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="shield-check" size={21} color="var(--blue-700)" strokeWidth={1.6} /></span>
                <div>
                  <h3 style={{ margin: '0 0 5px', fontSize: 'var(--fs-h4)', fontWeight: 500 }}>{c.t}</h3>
                  <p style={{ margin: 0, fontSize: 'var(--fs-sm)', color: 'var(--text-body)', lineHeight: 'var(--lh-relaxed)' }}>{c.d}</p>
                </div>
              </Card>
            </P.Reveal>
          ))}
        </div>
        <div style={{ marginTop: 36 }}>
          <h3 style={{ margin: '0 0 14px', fontSize: 'var(--fs-h4)', fontWeight: 500 }}>Coberturas adicionais e modalidades</h3>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {prod.extras.map((e) => <span key={e} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', color: 'var(--text-body)', background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-pill)', padding: '8px 16px' }}><Icon name="plus" size={14} color="var(--gold-600)" /> {e}</span>)}
          </div>
        </div>
      </div>
    </section>

    {/* COMO FUNCIONA */}
    <section style={{ ...P.sectionPad }}>
      <div style={P.wrap}>
        <P.SectionHead eyebrow="Contratação" title="Como funciona, em 4 passos" align="center" max="40ch" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }} className="fcs-steps-grid">
          {prod.steps.map((s, i) => (
            <P.Reveal key={i} delay={i * 60}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                <span style={{ fontFamily: 'var(--font-serif)', fontSize: 40, fontWeight: 300, color: 'var(--neutral-300)', lineHeight: 1 }}>{String(i + 1).padStart(2, '0')}</span>
                <h3 style={{ margin: 0, fontSize: 'var(--fs-h4)', fontWeight: 500 }}>{s.t}</h3>
                <p style={{ margin: 0, fontSize: 'var(--fs-sm)', color: 'var(--text-body)', lineHeight: 'var(--lh-relaxed)' }}>{s.d}</p>
              </div>
            </P.Reveal>
          ))}
        </div>
      </div>
    </section>

    {/* FORMULÁRIO + PROVA SOCIAL */}
    <section style={{ ...P.sectionPad, background: 'var(--surface-sunken)' }}>
      <div style={{ ...P.wrap, display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 48, alignItems: 'start' }} className="fcs-quote-grid">
        <ProdForm />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20, paddingTop: 6 }}>
          <P.Eyebrow>Por que a Flávio</P.Eyebrow>
          <h2 style={{ margin: 0, fontSize: 'var(--fs-h2)', fontWeight: 400, maxWidth: '16ch' }}>Consultoria de verdade, do início ao sinistro</h2>
          {[['git-compare', 'Comparamos 10+ seguradoras', 'Você recebe as melhores opções, não uma só.'], ['life-buoy', 'Presença no sinistro', 'Cuidamos da orientação técnica e da burocracia por você.'], ['clock', 'Retorno em 1 dia útil', 'Agilidade sem perder o cuidado no atendimento.']].map(([ic, t, d]) => (
            <div key={t} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <span style={{ width: 42, height: 42, flex: '0 0 auto', borderRadius: 'var(--radius-md)', background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={ic} size={19} color="var(--blue-700)" strokeWidth={1.6} /></span>
              <div><h3 style={{ margin: '2px 0 3px', fontSize: 'var(--fs-body)', fontWeight: 600 }}>{t}</h3><p style={{ margin: 0, fontSize: 'var(--fs-sm)', color: 'var(--text-muted)', lineHeight: 'var(--lh-relaxed)' }}>{d}</p></div>
            </div>
          ))}
          <Card padding="22px 24px" style={{ background: 'var(--surface-card)' }}>
            <p style={{ margin: '0 0 12px', fontFamily: 'var(--font-serif)', fontStyle: 'normal', fontSize: 'var(--fs-lead)', fontWeight: 300, color: 'var(--text-strong)', lineHeight: 1.5 }}>“{PD.TESTIMONIALS[0].quote}”</p>
            <span style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', fontWeight: 600, color: 'var(--blue-800)' }}>{PD.TESTIMONIALS[0].author}</span>
            <span style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-xs)', color: 'var(--text-muted)' }}> · {PD.TESTIMONIALS[0].role}</span>
          </Card>
        </div>
      </div>
    </section>

    {/* FAQ + RELACIONADOS */}
    <section style={{ ...P.sectionPad }}>
      <div style={{ ...P.wrap, display: 'grid', gridTemplateColumns: '0.85fr 1.15fr', gap: 56, alignItems: 'start' }} className="fcs-faq-grid">
        <div>
          <P.SectionHead eyebrow="Dúvidas frequentes" title={'Sobre ' + prod.title} intro="As perguntas mais comuns deste seguro." />
          {related.length > 0 && (
            <div>
              <span style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-eyebrow)', fontWeight: 700, letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase', color: 'var(--gold-600)' }}>Veja também</span>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
                {related.map((r) => (
                  <a key={r.slug} href={'produto.html?p=' + r.slug} style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--blue-700)', textDecoration: 'none', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', fontWeight: 500 }}><Icon name={r.icon} size={17} /> {r.title} <Icon name="arrow-right" size={15} /></a>
                ))}
              </div>
            </div>
          )}
        </div>
        <Card padding="8px 28px"><Accordion items={prod.faqs.map((f) => ({ q: f.q, a: f.a }))} defaultOpen={[0]} /></Card>
      </div>
    </section>

    <P.FinalCTA />
  </React.Fragment>
));
