/* global React, BezaLogo, Icon, Pill, fmt,
   BlockCard, Punch, BigStat, brl, brlK */
const { useState: useStateProp, useMemo: useMemoProp, useEffect: useEffectProp } = React;

/* ============================================================
   PROPOSAL GENERATOR · wizard conversacional → landing HTML →
   publica no WordPress (hoje mock, fácil de plugar API real)
   ============================================================ */

// BEZA:PROPOSAL-TEMPLATES
const PROPOSAL_TEMPLATES = {
  'soldado': {
    name: 'Pacote completo · conteúdo + vídeo longo',
    description: 'Reels + carrosseis + YouTube + relatório',
    monthly: 6800,
    deliverables: { reels: 8, carrosseis: 4, banners: 4, fotos: 4, youtube: 4 },
    bestFor: ['conteúdo cristão', 'liderança', 'autor', 'mentor'],
  },
  'standard': {
    name: 'Standard · profissional liberal',
    description: 'Reels + carrosseis + identidade',
    monthly: 4200,
    deliverables: { reels: 4, carrosseis: 4, banners: 2 },
    bestFor: ['arquitetura', 'design', 'advocacia', 'medicina'],
  },
  'premium-ecommerce': {
    name: 'Premium · e-commerce',
    description: 'Volume + tráfego pago + fotos + ROAS',
    monthly: 7800,
    deliverables: { reels: 12, carrosseis: 6, banners: 4, fotos: 4, ads: 1 },
    bestFor: ['e-commerce', 'moda', 'cosméticos', 'casa & decoração'],
  },
};

// Portfolio interno da Beza, puxado dinamicamente por segmento
const BEZA_PORTFOLIO = [
  { client: 'Soldado de Deus', segment: 'cristão',     metric: '687k alcance · abril 2026', highlight: 'Maior crescimento da agência em conteúdo cristão · +35k seguidores em 90d' },
  { client: 'Áurea Clínica',   segment: 'saúde',       metric: '+42% engajamento em 3m',     highlight: 'Clínica de longevidade · 0 → 12k seguidores qualificados' },
  { client: 'Maison Zelí',     segment: 'e-commerce',  metric: 'R$ 380k em vendas via Reels', highlight: 'E-commerce moda autoral · ticket médio 3x maior pós-Beza' },
  { client: 'Lumen Arquitetura', segment: 'arquitetura', metric: '12 projetos fechados via IG', highlight: 'Arquitetura residencial alto padrão · Reels assinados pelo arquiteto' },
  { client: 'Brady',           segment: 'B2B',         metric: '20 Reels/mês · 4.2M views',   highlight: 'Negócios B2B internacional · expansão para mercado americano' },
  { client: 'Pr. Anderson',    segment: 'cristão',     metric: '8k → 38k seguidores',         highlight: 'Pastor + autor · construção de autoridade digital em 8 meses' },
];

// Depoimentos reais (mock no padrão Beza)
const BEZA_TESTIMONIALS = [
  { client: 'Robert L. Grier', brand: 'Soldado de Deus', quote: 'Em 8 meses, a Beza fez o que outras 3 agências não conseguiram em 2 anos. Estrutura real, sem firula.', role: 'Pastor e empresário' },
  { client: 'Dra. Renata Bonvechio', brand: 'Áurea Clínica', quote: 'Eles entenderam o tom que eu queria desde a primeira conversa. Hoje meu Instagram é uma extensão da clínica.', role: 'Médica geriatra' },
  { client: 'Zelí Almeida', brand: 'Maison Zelí', quote: 'Triplicou o ticket médio sem aumentar o tráfego. Eles olham o todo, não só o post.', role: 'Fundadora' },
];

const PROPOSAL_LS_KEY = 'beza_proposals_published_v1';

function loadPublished() {
  try { return JSON.parse(localStorage.getItem(PROPOSAL_LS_KEY) || '[]'); } catch { return []; }
}
function savePublished(arr) {
  try { localStorage.setItem(PROPOSAL_LS_KEY, JSON.stringify(arr)); } catch (e) {}
}

/* ============================================================
   GERADOR · wizard com 8 perguntas → preview → publicar
   ============================================================ */
const WIZARD_QUESTIONS = [
  { id: 'leadName',    label: 'Quem é o contato?',                placeholder: 'ex: Carolina Sotero',                  required: true },
  { id: 'leadCompany', label: 'Qual o nome da marca/empresa?',    placeholder: 'ex: Lumen Arquitetura',                required: true },
  { id: 'segment',     label: 'Qual o segmento?',                 type: 'select', options: ['arquitetura', 'saúde', 'e-commerce', 'moda', 'consultoria', 'religioso', 'food', 'outro'] },
  { id: 'channels',    label: 'Onde a marca está hoje?',          type: 'checkboxes', options: [
    { id: 'instagram', label: 'Instagram (orgânico)' },
    { id: 'reels',     label: 'Já produz Reels' },
    { id: 'youtube',   label: 'YouTube' },
    { id: 'ads',       label: 'Tráfego pago' },
    { id: 'site',      label: 'Site próprio' },
    { id: 'zero',      label: 'Começando do zero' },
  ]},
  { id: 'pain',        label: 'Qual o desafio principal?',         placeholder: 'Em 1-2 frases · ex: o conteúdo não traduz o nível de serviço que entregamos',  multiline: true },
  { id: 'goal',        label: 'Onde a marca quer chegar em 6 meses?', placeholder: 'ex: ser referência regional · ou triplicar consultas via Instagram', multiline: true },
  { id: 'template',    label: 'Qual pacote faz mais sentido?',     type: 'template-picker' },
  { id: 'tone',        label: 'Tom da proposta',                   type: 'radio', options: [
    { id: 'editorial',  label: 'Editorial · sóbrio',          desc: 'foco em estratégia + entrega' },
    { id: 'consultivo', label: 'Consultivo · diagnóstico',    desc: 'aprofunda no problema antes da oferta' },
    { id: 'direto',     label: 'Direto · resultado',          desc: 'cases primeiro · números primeiro' },
  ]},
];

function SectionPropostasV2() {
  const [view, setView] = useStateProp('wizard'); // wizard · published

  return (
    <div>
      <div style={{
        display: 'inline-flex', gap: 4, padding: 4,
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 'var(--r-pill)', marginBottom: 'var(--space-5)',
      }}>
        {[
          { id: 'wizard',    label: '✨ Gerar proposta' },
          { id: 'published', label: 'Propostas ativas' },
        ].map(v => {
          const active = view === v.id;
          return (
            <button key={v.id} onClick={() => setView(v.id)} style={{
              appearance: 'none', border: 'none',
              background: active ? 'var(--accent)' : 'transparent',
              color: active ? '#fff' : 'var(--text-muted)',
              padding: '8px 16px', fontSize: 13,
              fontWeight: active ? 500 : 400,
              borderRadius: 'var(--r-pill)', cursor: 'pointer',
              fontFamily: 'inherit',
            }}>{v.label}</button>
          );
        })}
      </div>

      {view === 'wizard' ? <ProposalWizard /> : <PublishedList />}
    </div>
  );
}

/* ============================================================
   WIZARD · pergunta por pergunta
   ============================================================ */
function ProposalWizard() {
  const [step, setStep] = useStateProp(0);
  const [answers, setAnswers] = useStateProp({});
  const [generated, setGenerated] = useStateProp(false);
  const [publishing, setPublishing] = useStateProp(false);
  const [publishedUrl, setPublishedUrl] = useStateProp(null);

  const q = WIZARD_QUESTIONS[step];
  const isLast = step === WIZARD_QUESTIONS.length - 1;
  const progress = ((step + 1) / WIZARD_QUESTIONS.length) * 100;

  const update = (v) => setAnswers(a => ({ ...a, [q.id]: v }));
  const next = () => isLast ? setGenerated(true) : setStep(s => s + 1);
  const prev = () => setStep(s => Math.max(0, s - 1));
  const canAdvance = q.required === false || answers[q.id] != null;

  const startOver = () => { setStep(0); setAnswers({}); setGenerated(false); setPublishedUrl(null); };

  const publishToWordPress = () => {
    setPublishing(true);
    // Mock da chamada à WP REST API
    setTimeout(() => {
      const slug = (answers.leadCompany || 'cliente').toLowerCase()
        .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
        .replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
      const url = `https://beza.media/proposta-${slug}/`;

      const entry = {
        id: 'p-' + Date.now(),
        ...answers,
        url, slug,
        publishedAt: new Date().toISOString(),
        opens: 0, status: 'enviada',
      };
      const all = loadPublished();
      savePublished([entry, ...all]);

      setPublishedUrl(url);
      setPublishing(false);
    }, 2200);
  };

  if (generated) {
    return <ProposalPreview answers={answers} onStartOver={startOver} onPublish={publishToWordPress} publishing={publishing} publishedUrl={publishedUrl} />;
  }

  return (
    <BlockCard kicker="✨ wizard · 8 perguntas" title="**Vamos montar** essa proposta">
      <p style={{ margin: '0 0 18px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
        Responde as 8 perguntas e o Claude monta a proposta inteira na linguagem da Beza · landing HTML pronta pra publicar em <code style={{ color: 'var(--accent)' }}>beza.media/proposta-[nome]</code>.
      </p>

      {/* Progress */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
          <span className="t-overline" style={{ color: 'var(--text-faint)' }}>
            pergunta {step + 1} de {WIZARD_QUESTIONS.length}
          </span>
          <span style={{ fontSize: 12, color: 'var(--accent)', fontWeight: 500 }}>{Math.round(progress)}%</span>
        </div>
        <div style={{ height: 6, background: 'var(--surface-soft)', borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)' }}>
          <div style={{
            height: '100%', width: progress + '%',
            background: 'linear-gradient(90deg, var(--beza-purple), var(--beza-deep))',
            borderRadius: 999, transition: 'width var(--t-slow)',
          }} />
        </div>
      </div>

      {/* Pergunta */}
      <div style={{
        padding: 'var(--space-5)',
        background: 'linear-gradient(135deg, rgba(154,155,229,0.06), rgba(154,155,229,0.01))',
        border: '1px solid var(--border-strong)',
        borderRadius: 'var(--r-card-lg)',
        minHeight: 260,
      }}>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 8 }}>
          0{step + 1}
        </div>
        <h3 className="t-h2" style={{ margin: '0 0 24px', color: 'var(--text)' }}>
          <span className="t-light">{q.label}</span>
        </h3>

        <WizardInput q={q} value={answers[q.id]} onChange={update} answers={answers} />
      </div>

      {/* Actions */}
      <div style={{
        marginTop: 24, display: 'flex', justifyContent: 'space-between', gap: 12,
      }}>
        <button onClick={prev} disabled={step === 0} style={{
          appearance: 'none', border: '1px solid var(--border-strong)',
          background: 'transparent', color: 'var(--text-muted)',
          padding: '10px 16px', borderRadius: 'var(--r-btn)',
          fontSize: 13, fontFamily: 'inherit',
          cursor: step === 0 ? 'not-allowed' : 'pointer',
          opacity: step === 0 ? 0.5 : 1,
        }}>← Voltar</button>
        <button onClick={next} disabled={!canAdvance} style={{
          appearance: 'none', border: '1px solid var(--accent)',
          background: canAdvance ? 'var(--accent)' : 'var(--surface)',
          color: canAdvance ? '#fff' : 'var(--text-faint)',
          padding: '10px 20px', borderRadius: 'var(--r-btn)',
          fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
          cursor: canAdvance ? 'pointer' : 'not-allowed',
        }}>
          {isLast ? '✨ Gerar proposta →' : 'Próxima →'}
        </button>
      </div>
    </BlockCard>
  );
}

function WizardInput({ q, value, onChange, answers }) {
  if (q.type === 'select') {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 8 }}>
        {q.options.map(o => {
          const active = value === o;
          return (
            <button key={o} onClick={() => onChange(o)} style={{
              appearance: 'none', textAlign: 'left',
              padding: '12px 16px',
              background: active ? 'var(--accent-soft)' : 'var(--surface)',
              border: '1px solid', borderColor: active ? 'var(--accent)' : 'var(--border)',
              color: active ? 'var(--accent)' : 'var(--text)',
              borderRadius: 'var(--r-card)',
              fontSize: 14, fontFamily: 'inherit', cursor: 'pointer',
              fontWeight: active ? 500 : 400,
              textTransform: 'capitalize',
            }}>{o}</button>
          );
        })}
      </div>
    );
  }
  if (q.type === 'checkboxes') {
    const current = value || [];
    const toggle = (id) => {
      onChange(current.includes(id) ? current.filter(x => x !== id) : [...current, id]);
    };
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 8 }}>
        {q.options.map(o => {
          const active = current.includes(o.id);
          return (
            <button key={o.id} onClick={() => toggle(o.id)} style={{
              appearance: 'none', textAlign: 'left',
              padding: '12px 16px',
              background: active ? 'var(--accent-soft)' : 'var(--surface)',
              border: '1px solid', borderColor: active ? 'var(--accent)' : 'var(--border)',
              color: active ? 'var(--accent)' : 'var(--text)',
              borderRadius: 'var(--r-card)',
              fontSize: 14, fontFamily: 'inherit', cursor: 'pointer',
              fontWeight: active ? 500 : 400,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <span style={{
                width: 18, height: 18, borderRadius: 4,
                background: active ? 'var(--accent)' : 'transparent',
                border: '1.5px solid', borderColor: active ? 'var(--accent)' : 'var(--border-strong)',
                color: '#fff', fontSize: 11, fontWeight: 700,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>{active ? '✓' : ''}</span>
              {o.label}
            </button>
          );
        })}
      </div>
    );
  }
  if (q.type === 'radio') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {q.options.map(o => {
          const active = value === o.id;
          return (
            <button key={o.id} onClick={() => onChange(o.id)} style={{
              appearance: 'none', textAlign: 'left',
              padding: '14px 18px',
              background: active ? 'var(--accent-soft)' : 'var(--surface)',
              border: '1px solid', borderColor: active ? 'var(--accent)' : 'var(--border)',
              borderRadius: 'var(--r-card)',
              fontSize: 14, fontFamily: 'inherit', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', gap: 4,
            }}>
              <span style={{ fontWeight: 500, color: active ? 'var(--accent)' : 'var(--text)' }}>{o.label}</span>
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{o.desc}</span>
            </button>
          );
        })}
      </div>
    );
  }
  if (q.type === 'template-picker') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {Object.entries(PROPOSAL_TEMPLATES).map(([id, t]) => {
          const active = value === id;
          const recommendedForSegment = t.bestFor.includes(answers.segment);
          return (
            <button key={id} onClick={() => onChange(id)} style={{
              appearance: 'none', textAlign: 'left',
              padding: '14px 18px',
              background: active ? 'var(--accent-soft)' : 'var(--surface)',
              border: '1px solid', borderColor: active ? 'var(--accent)' : 'var(--border)',
              borderRadius: 'var(--r-card)',
              fontFamily: 'inherit', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', gap: 6, position: 'relative',
            }}>
              {recommendedForSegment && (
                <span style={{
                  position: 'absolute', top: 10, right: 10,
                  fontSize: 9, color: 'var(--success)', padding: '2px 8px',
                  background: 'rgba(111,200,120,0.10)', border: '1px solid rgba(111,200,120,0.30)',
                  borderRadius: 999, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 500,
                }}>★ recomendado pro segmento</span>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontSize: 15, fontWeight: 500, color: active ? 'var(--accent)' : 'var(--text)' }}>{t.name}</span>
                <span className="num" style={{ fontSize: 14, fontWeight: 500, color: active ? 'var(--accent)' : 'var(--text-muted)' }}>
                  {brlK(t.monthly)}/mês
                </span>
              </div>
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t.description}</span>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
                {Object.entries(t.deliverables).map(([k, v]) => (
                  <Pill key={k}>{v} {k}</Pill>
                ))}
              </div>
            </button>
          );
        })}
      </div>
    );
  }
  const Tag = q.multiline ? 'textarea' : 'input';
  return (
    <Tag
      type={q.multiline ? undefined : 'text'}
      value={value || ''}
      onChange={(e) => onChange(e.target.value)}
      placeholder={q.placeholder}
      rows={q.multiline ? 4 : undefined}
      autoFocus
      style={{
        width: '100%', appearance: 'none',
        border: '1px solid var(--border-strong)',
        background: 'var(--surface)', color: 'var(--text)',
        padding: '14px 16px', borderRadius: 'var(--r-btn)',
        fontFamily: 'inherit', fontSize: 16, lineHeight: 1.5,
        outline: 'none', resize: q.multiline ? 'vertical' : undefined,
        minHeight: q.multiline ? 100 : undefined,
      }}
    />
  );
}

/* ============================================================
   PREVIEW · landing HTML completa
   ============================================================ */
function ProposalPreview({ answers, onStartOver, onPublish, publishing, publishedUrl }) {
  const template = PROPOSAL_TEMPLATES[answers.template] || PROPOSAL_TEMPLATES['standard'];
  // Portfolio do mesmo segmento (até 3 itens)
  const relatedPortfolio = BEZA_PORTFOLIO.filter(p => p.segment === answers.segment).slice(0, 3);
  const fallbackPortfolio = BEZA_PORTFOLIO.slice(0, 3);
  const showPortfolio = relatedPortfolio.length > 0 ? relatedPortfolio : fallbackPortfolio;

  const slug = (answers.leadCompany || 'cliente').toLowerCase()
    .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
  const previewUrl = `beza.media/proposta-${slug}`;

  return (
    <div>
      {/* TOOLBAR */}
      <BlockCard>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 4 }}>
              {publishedUrl ? '✓ publicada no WordPress' : 'preview · ainda não publicada'}
            </div>
            <h3 className="t-h3" style={{ margin: 0 }}>
              <span className="t-light">Proposta para </span>
              <span className="punch">{answers.leadCompany}</span>
            </h3>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4, fontFamily: 'monospace' }}>
              {publishedUrl || previewUrl}
            </div>
          </div>
          <div style={{ display: 'inline-flex', gap: 8, flexWrap: 'wrap' }}>
            <button onClick={onStartOver} style={btnGhost2}>↺ recomeçar</button>
            <button onClick={() => navigator.clipboard?.writeText(publishedUrl || `https://${previewUrl}`)} style={btnGhost2}>
              ⎘ copiar link
            </button>
            <button onClick={() => window.print()} style={btnGhost2}>↓ PDF</button>
            {!publishedUrl && (
              <button onClick={onPublish} disabled={publishing} style={{
                appearance: 'none', border: '1px solid var(--accent)',
                background: publishing ? 'var(--surface)' : 'var(--accent)',
                color: publishing ? 'var(--text-faint)' : '#fff',
                padding: '10px 18px', borderRadius: 'var(--r-btn)',
                fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
                cursor: publishing ? 'wait' : 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 8,
              }}>
                {publishing ? '⊙ publicando...' : '✨ Publicar no WordPress'}
              </button>
            )}
            {publishedUrl && (
              <a href={publishedUrl} target="_blank" rel="noopener noreferrer" style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                color: '#fff', textDecoration: 'none',
                padding: '10px 18px', borderRadius: 'var(--r-btn)',
                background: 'linear-gradient(135deg, var(--success), #4FA858)',
                fontSize: 13, fontWeight: 500,
              }}>
                ✓ Abrir no site →
              </a>
            )}
          </div>
        </div>

        {publishing && (
          <div style={{ marginTop: 18, padding: 14, background: 'var(--accent-soft)', border: '1px solid rgba(154,155,229,0.30)', borderRadius: 'var(--r-card)', fontSize: 13, color: 'var(--text)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)', animation: 'pulse 1s infinite' }} />
              <span style={{ fontWeight: 500 }}>Publicando em beza.media...</span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', fontFamily: 'monospace', lineHeight: 1.7 }}>
              {`> POST /wp-json/wp/v2/proposta\n> { title: "${answers.leadCompany}", slug: "${slug}", ... }\n> aguardando resposta do WordPress...`}
            </div>
          </div>
        )}

        {publishedUrl && (
          <div style={{ marginTop: 18, padding: 14, background: 'rgba(111,200,120,0.10)', border: '1px solid rgba(111,200,120,0.30)', borderRadius: 'var(--r-card)' }}>
            <div className="t-overline" style={{ color: 'var(--success)', marginBottom: 6 }}>✓ proposta publicada</div>
            <div style={{ fontSize: 13, color: 'var(--text)', lineHeight: 1.6 }}>
              Link rastreável criado. Pode copiar e mandar pro {answers.leadName} agora. Quando o cliente abrir, o sistema notifica na <strong style={{ color: 'var(--accent)' }}>aba de Alertas</strong>.
            </div>
          </div>
        )}
      </BlockCard>

      {/* LANDING PREVIEW */}
      <div id="proposal-landing" style={{
        padding: 'var(--space-6)',
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-card-lg)',
        marginBottom: 'var(--space-5)',
      }}>
        <ProposalLanding answers={answers} template={template} portfolio={showPortfolio} />
      </div>

      <div style={{
        padding: 12, fontSize: 11, color: 'var(--text-faint)',
        background: 'var(--surface-soft)', border: '1px dashed var(--border-strong)',
        borderRadius: 'var(--r-btn)',
      }}>
        <strong style={{ color: 'var(--text)' }}>Pro Claude Code:</strong> ao publicar, fazer <code style={{ color: 'var(--accent)' }}>POST</code> em <code style={{ color: 'var(--accent)' }}>/wp-json/wp/v2/proposta</code> com o slug + HTML completo da landing (vide componente <code>ProposalLanding</code>). Precisa de Application Password do WP e custom post type "proposta" registrado no functions.php.
      </div>
    </div>
  );
}

const btnGhost2 = {
  appearance: 'none', border: '1px solid var(--border-strong)',
  background: 'var(--surface)', color: 'var(--text-muted)',
  padding: '10px 14px', borderRadius: 'var(--r-btn)',
  fontSize: 13, fontFamily: 'inherit', cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', gap: 6,
};

/* ============================================================
   LANDING DA PROPOSTA · estrutura HTML pronta pra WordPress
   ============================================================ */
function ProposalLanding({ answers, template, portfolio }) {
  const isPremium = answers.template === 'premium-ecommerce';
  return (
    <div style={{
      maxWidth: 900, margin: '0 auto',
      fontFamily: "'IBM Plex Sans', sans-serif",
    }}>
      {/* HERO */}
      <section style={{
        padding: 'var(--space-7) var(--space-5)',
        background: 'linear-gradient(135deg, #0A0A0A 0%, #1E1E2E 100%)',
        color: '#fff',
        borderRadius: 'var(--r-card-lg)',
        marginBottom: 'var(--space-5)',
        position: 'relative', overflow: 'hidden',
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', top: '-40%', right: '-15%',
          width: 600, height: 600, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(154,155,229,0.30), transparent 60%)',
          filter: 'blur(60px)', pointerEvents: 'none',
        }} />
        <div style={{ position: 'relative' }}>
          <div style={{
            fontSize: 11, fontWeight: 500, letterSpacing: '0.12em',
            textTransform: 'uppercase', color: 'rgba(154,155,229,0.9)', marginBottom: 16,
          }}>
            Proposta Comercial · Beza Media
          </div>
          <h1 style={{
            margin: '0 0 16px',
            fontSize: 'clamp(40px, 6vw, 64px)',
            fontWeight: 300, letterSpacing: '-0.02em', lineHeight: 1.1,
            textWrap: 'pretty',
          }}>
            <span style={{ opacity: 0.85 }}>Construindo estruturas para </span>
            <span style={{ fontWeight: 500, color: '#9A9BE5' }}>{answers.leadCompany}</span>
            <span style={{ opacity: 0.85 }}>.</span>
          </h1>
          <p style={{ margin: 0, fontSize: 17, lineHeight: 1.6, opacity: 0.78, maxWidth: 580 }}>
            Uma proposta pensada especificamente pro momento da marca. Sem template genérico, sem promessa solta. Só estrutura.
          </p>
        </div>
      </section>

      {/* DIAGNÓSTICO */}
      {answers.pain && (
        <LandingSection num="01" title="O que vimos">
          <p style={{ fontSize: 17, lineHeight: 1.7, color: 'var(--text)' }}>
            {answers.leadName}, {answers.pain}
          </p>
          <p style={{ fontSize: 17, lineHeight: 1.7, color: 'var(--text)', marginTop: 12 }}>
            É o tipo de problema que a Beza resolve: <span style={{ fontWeight: 500, color: 'var(--accent)' }}>dar consistência sem perder a alma da marca</span>, construir estrutura sem engessar a voz.
          </p>
        </LandingSection>
      )}

      {/* OBJETIVO */}
      {answers.goal && (
        <LandingSection num="02" title="Onde vamos chegar">
          <blockquote style={{
            margin: 0, padding: '20px 24px',
            background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
            border: '1px solid rgba(154,155,229,0.30)',
            borderLeft: '3px solid var(--accent)',
            borderRadius: 'var(--r-card)',
            fontSize: 18, fontStyle: 'italic', fontWeight: 300,
            color: 'var(--text)', lineHeight: 1.5,
          }}>
            "{answers.goal}"
          </blockquote>
        </LandingSection>
      )}

      {/* PROPOSTA */}
      <LandingSection num="03" title="Nossa proposta">
        <div style={{ marginBottom: 18 }}>
          <h3 style={{ margin: '0 0 8px', fontSize: 22, fontWeight: 500, color: 'var(--text)' }}>
            {template.name}
          </h3>
          <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)' }}>
            {template.description}
          </p>
        </div>

        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12,
        }}>
          {Object.entries(template.deliverables).map(([k, v]) => (
            <div key={k} style={{
              padding: 18, textAlign: 'center',
              background: 'var(--accent-soft)',
              border: '1px solid rgba(154,155,229,0.30)',
              borderRadius: 'var(--r-card)',
            }}>
              <div className="num" style={{ fontSize: 32, fontWeight: 500, color: 'var(--accent)', lineHeight: 1 }}>{v}</div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 6, textTransform: 'capitalize' }}>{k}</div>
              <div style={{ fontSize: 10, color: 'var(--text-faint)', marginTop: 2 }}>por mês</div>
            </div>
          ))}
        </div>
      </LandingSection>

      {/* PORTFOLIO */}
      <LandingSection num="04" title={`Resultados em ${answers.segment || 'agências'}`}>
        <p style={{ margin: '0 0 18px', fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.6 }}>
          Clientes que confiaram na Beza em segmento similar ao seu. Números reais, sem retoque.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {portfolio.map((p, i) => (
            <div key={i} style={{
              padding: 'var(--space-4)',
              background: 'var(--surface-soft)',
              border: '1px solid var(--border)',
              borderLeft: '3px solid var(--accent)',
              borderRadius: 'var(--r-card)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, marginBottom: 6, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 16, fontWeight: 500, color: 'var(--text)' }}>{p.client}</span>
                <span className="num" style={{ fontSize: 14, fontWeight: 500, color: 'var(--accent)' }}>{p.metric}</span>
              </div>
              <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.6 }}>{p.highlight}</p>
            </div>
          ))}
        </div>
      </LandingSection>

      {/* DEPOIMENTOS */}
      <LandingSection num="05" title="O que dizem">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          {BEZA_TESTIMONIALS.map((t, i) => (
            <div key={i} style={{
              padding: 20,
              background: 'var(--surface-soft)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
            }}>
              <p style={{
                margin: '0 0 14px', fontSize: 15, lineHeight: 1.5,
                color: 'var(--text)', fontStyle: 'italic', fontWeight: 300,
              }}>
                "{t.quote}"
              </p>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
                <div style={{
                  width: 36, height: 36, borderRadius: '50%',
                  background: 'linear-gradient(135deg, var(--accent), var(--beza-deep))',
                  color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 500, fontSize: 14,
                }}>{t.client[0]}</div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{t.client}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>{t.role} · {t.brand}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </LandingSection>

      {/* INVESTIMENTO */}
      <LandingSection num="06" title="Investimento">
        <div style={{
          padding: 'var(--space-6)',
          background: 'linear-gradient(135deg, var(--beza-deep), var(--beza-purple))',
          color: '#fff', borderRadius: 'var(--r-card-lg)',
          position: 'relative', overflow: 'hidden',
        }}>
          <div aria-hidden="true" style={{
            position: 'absolute', top: '-50%', right: '-15%',
            width: 400, height: 400, borderRadius: '50%',
            background: 'radial-gradient(circle, rgba(255,255,255,0.18), transparent 60%)',
            filter: 'blur(40px)', pointerEvents: 'none',
          }} />
          <div style={{ position: 'relative' }}>
            <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.85, marginBottom: 12 }}>
              Mensalidade
            </div>
            <div className="num" style={{ fontSize: 'clamp(48px, 6vw, 64px)', fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em' }}>
              {brl(template.monthly)}
            </div>
            <div style={{ fontSize: 14, opacity: 0.85, marginTop: 12 }}>
              Contrato mínimo de 6 meses · pagamento dia 5 · sem fidelidade após o período.
            </div>
          </div>
        </div>
      </LandingSection>

      {/* CTA */}
      <section style={{
        padding: 'var(--space-7) var(--space-5)',
        textAlign: 'center',
        background: 'var(--surface-soft)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-card-lg)',
      }}>
        <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 14 }}>
          07 · próximo passo
        </div>
        <h2 style={{ margin: '0 0 18px', fontSize: 'clamp(28px, 4vw, 36px)', fontWeight: 400, textWrap: 'pretty' }}>
          <span style={{ color: 'var(--text-muted)', fontWeight: 300 }}>Se fizer sentido, </span>
          <span style={{ color: 'var(--accent)', fontWeight: 500 }}>vamos conversar</span>
          <span style={{ color: 'var(--text-muted)', fontWeight: 300 }}>.</span>
        </h2>
        <p style={{ margin: '0 auto 28px', fontSize: 15, color: 'var(--text-muted)', lineHeight: 1.6, maxWidth: 480 }}>
          Uma call de 30 minutos. Alinhamos detalhes, definimos o calendário inicial e o time já entra em produção na semana seguinte.
        </p>
        <button style={{
          appearance: 'none', border: '1px solid var(--accent)',
          background: 'var(--accent)', color: '#fff',
          padding: '14px 32px', borderRadius: 'var(--r-pill)',
          fontSize: 15, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
          boxShadow: '0 8px 24px rgba(154,155,229,0.30)',
        }}>
          ✓ Aceitar e agendar call →
        </button>
        <div style={{ marginTop: 20, fontSize: 11, color: 'var(--text-faint)', fontStyle: 'italic' }}>
          Proposta válida por 14 dias · Beza Media · Construindo estruturas para o extraordinário.
        </div>
      </section>
    </div>
  );
}

function LandingSection({ num, title, children }) {
  return (
    <section style={{ marginBottom: 'var(--space-6)' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 18 }}>
        <span style={{
          fontSize: 11, color: 'var(--accent)', fontWeight: 500,
          letterSpacing: '0.12em', fontVariantNumeric: 'tabular-nums',
        }}>{num}</span>
        <h2 style={{ margin: 0, fontSize: 'clamp(22px, 3vw, 28px)', fontWeight: 400, color: 'var(--text)', letterSpacing: '-0.01em' }}>
          {title}
        </h2>
      </div>
      <div>{children}</div>
    </section>
  );
}

/* ============================================================
   PUBLISHED LIST · propostas ativas no WP
   ============================================================ */
function PublishedList() {
  const [items, setItems] = useStateProp(() => loadPublished());

  useEffectProp(() => {
    const id = setInterval(() => setItems(loadPublished()), 2000);
    return () => clearInterval(id);
  }, []);

  if (items.length === 0) {
    return (
      <BlockCard>
        <div style={{ padding: 'var(--space-6)', textAlign: 'center', color: 'var(--text-muted)' }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>📝</div>
          <h3 style={{ margin: '0 0 8px', fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>Nenhuma proposta publicada ainda</h3>
          <p style={{ margin: 0, fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6 }}>
            Gere uma proposta pelo wizard e publique no WordPress. Elas aparecem aqui pra rastrear aberturas e status.
          </p>
        </div>
      </BlockCard>
    );
  }

  return (
    <BlockCard kicker="ativas no beza.media" title="**Propostas** publicadas">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map(p => (
          <div key={p.id} style={{
            padding: 'var(--space-4)',
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderLeft: '3px solid var(--accent)',
            borderRadius: 'var(--r-card)',
            display: 'grid', gridTemplateColumns: '1fr auto', gap: 14, alignItems: 'flex-start',
          }}>
            <div>
              <div style={{ display: 'flex', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                <Pill tone="success">✓ publicada</Pill>
                <Pill>{PROPOSAL_TEMPLATES[p.template]?.name || 'pacote'}</Pill>
              </div>
              <div style={{ fontSize: 16, fontWeight: 500, color: 'var(--text)' }}>{p.leadCompany}</div>
              <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 2 }}>{p.leadName} · {p.segment}</div>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 6, fontFamily: 'monospace' }}>{p.url}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end' }}>
              <span className="num" style={{ fontSize: 18, fontWeight: 500, color: 'var(--accent)' }}>
                {brl(PROPOSAL_TEMPLATES[p.template]?.monthly || 0)}<span style={{ fontSize: 11, color: 'var(--text-faint)' }}>/mês</span>
              </span>
              <a href={p.url} target="_blank" rel="noopener noreferrer" style={{
                fontSize: 12, color: 'var(--accent)', textDecoration: 'none', fontWeight: 500,
              }}>abrir no site ↗</a>
            </div>
          </div>
        ))}
      </div>
    </BlockCard>
  );
}

Object.assign(window, { SectionPropostasV2, ProposalWizard, ProposalPreview, ProposalLanding, PublishedList });
