// Components for Quiz Salário-Maternidade.

const Icon = ({ name, size = 20, stroke = 1.75 }) => {
  const props = {
    width: size, height: size, viewBox: '0 0 24 24',
    fill: 'none', stroke: 'currentColor', strokeWidth: stroke,
    strokeLinecap: 'round', strokeLinejoin: 'round',
  };
  switch (name) {
    case 'arrow-left': return <svg {...props}><path d="M15 6l-6 6 6 6"/></svg>;
    case 'arrow-right': return <svg {...props}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case 'chev-right': return <svg {...props}><path d="M9 6l6 6-6 6"/></svg>;
    case 'check': return <svg {...props}><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>;
    case 'check-circle': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M8 12.5l3 3 5-6"/></svg>;
    case 'shield': return <svg {...props}><path d="M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6l8-3z"/><path d="M9 12l2 2 4-4"/></svg>;
    case 'lock': return <svg {...props}><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 1 1 8 0v4"/></svg>;
    case 'clock': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case 'wifi': return <svg {...props}><path d="M2 9a16 16 0 0 1 20 0"/><path d="M5 12.5a11 11 0 0 1 14 0"/><path d="M8.5 16a6 6 0 0 1 7 0"/><circle cx="12" cy="19" r="1.2" fill="currentColor"/></svg>;
    case 'baby': return <svg {...props}><circle cx="12" cy="9" r="4"/><path d="M9 8.5h.01M15 8.5h.01" strokeWidth="2.5"/><path d="M9.5 11.5c.7.7 1.6 1 2.5 1s1.8-.3 2.5-1"/><path d="M5 21c1-3 4-5 7-5s6 2 7 5"/></svg>;
    case 'belly': return <svg {...props}><path d="M9 4c-3 0-5 2.5-5 6 0 2 .8 3.7 2 5v4h2v-2.5h6V19h2v-4c1.2-1.3 2-3 2-5 0-3.5-2-6-5-6"/><circle cx="13" cy="11" r="0.8" fill="currentColor"/></svg>;
    case 'briefcase': return <svg {...props}><rect x="3" y="7" width="18" height="13" rx="2"/><path d="M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/><path d="M3 13h18"/></svg>;
    case 'home': return <svg {...props}><path d="M4 11l8-7 8 7v9a1 1 0 0 1-1 1h-4v-6h-6v6H5a1 1 0 0 1-1-1z"/></svg>;
    case 'id-card': return <svg {...props}><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="9" cy="11" r="2"/><path d="M14 10h4M14 13h3M6 16c0-1.5 1.5-2.5 3-2.5s3 1 3 2.5"/></svg>;
    case 'store': return <svg {...props}><path d="M3 9l1-5h16l1 5"/><path d="M3 9v11h18V9"/><path d="M3 9c0 1.5 1.5 3 3 3s3-1.5 3-3 1.5 3 3 3 3-1.5 3-3 1.5 3 3 3 3-1.5 3-3"/></svg>;
    case 'building': return <svg {...props}><rect x="4" y="3" width="16" height="18" rx="1"/><path d="M9 7h.01M15 7h.01M9 11h.01M15 11h.01M9 15h.01M15 15h.01M10 21v-4h4v4"/></svg>;
    case 'heart-hand': return <svg {...props}><path d="M12 21s-7-4.3-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 11c0 5.7-7 10-7 10z"/></svg>;
    case 'unemployed': return <svg {...props}><rect x="3" y="7" width="18" height="13" rx="2"/><path d="M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/><path d="M3 13h18"/><path d="M8 16l8 0" strokeWidth="2.5"/></svg>;
    case 'cal-x': return <svg {...props}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4M9.5 14.5l5 5M14.5 14.5l-5 5"/></svg>;
    case 'whatsapp': return <svg viewBox="0 0 24 24" width={size} height={size} fill="currentColor" fillRule="evenodd" clipRule="evenodd"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>;
    case 'user': return <svg {...props}><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></svg>;
    case 'sprout': return <svg {...props}><path d="M12 21v-7"/><path d="M12 14c0-3 2-6 6-6 0 4-2.5 6-6 6z"/><path d="M12 14c0-3-2-6-6-6 0 4 2.5 6 6 6z"/></svg>;
    case 'heart': return <svg {...props}><path d="M12 20s-7-4.3-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.7-7 10-7 10z"/></svg>;
    case 'sun': return <svg {...props}><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4L7 17M17 7l1.4-1.4"/></svg>;
    case 'info': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M12 8v.01M12 11v5"/></svg>;
    case 'help': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 1 1 3.5 2.3c-.6.3-1 .9-1 1.7v.5M12 17v.01"/></svg>;
    case 'doc': return <svg {...props}><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6M8 13h8M8 17h5"/></svg>;
    case 'sparkle': return <svg {...props}><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8L12 3z"/></svg>;
    case 'sun-rise': return <svg {...props}><path d="M3 17h18M5 17a7 7 0 0 1 14 0M12 4v3M5 9l1.5 1.5M19 9l-1.5 1.5M2 14h2M20 14h2"/></svg>;
    default: return null;
  }
};

const StatusBar = () => (
  <div className="statusbar">
    <span>9:41</span>
    <div className="sb-icons">
      <svg width="17" height="11" viewBox="0 0 17 11" fill="currentColor"><rect x="0" y="6" width="3" height="5" rx="0.5"/><rect x="4.5" y="4" width="3" height="7" rx="0.5"/><rect x="9" y="2" width="3" height="9" rx="0.5"/><rect x="13.5" y="0" width="3" height="11" rx="0.5"/></svg>
      <svg width="15" height="11" viewBox="0 0 15 11" fill="none" stroke="currentColor" strokeWidth="1.2"><path d="M1 4.5a8 8 0 0 1 13 0M3 6.5a5 5 0 0 1 9 0M5.5 8.5a2 2 0 0 1 4 0" strokeLinecap="round"/></svg>
      <svg width="25" height="11" viewBox="0 0 25 11" fill="none"><rect x="0.5" y="0.5" width="21" height="10" rx="2.5" stroke="currentColor" opacity="0.4"/><rect x="2" y="2" width="16" height="7" rx="1" fill="currentColor"/><rect x="22.5" y="3.5" width="1.5" height="4" rx="0.5" fill="currentColor" opacity="0.4"/></svg>
    </div>
  </div>
);

const LogoMark = ({ color = 'currentColor', size = 22 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <path d="M16 6c5 0 9 4 9 9.5S21 25 16 25s-9-4.5-9-9.5S11 6 16 6z" fill={color} opacity="0.25"/>
    <circle cx="16" cy="15" r="4.5" fill={color}/>
    <path d="M19 11.5c1.5-1.5 3.5-1.5 5-.5-1 2-2.5 3-4 3" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const TopChrome = ({ step, total, onBack, showBack = true }) => {
  if (step === 0) return null;
  return (
    <div className="top-chrome">
      <button className="back-btn" onClick={onBack} aria-label="Voltar"
              style={{visibility: showBack ? 'visible' : 'hidden'}}>
        <Icon name="arrow-left" size={20}/>
      </button>
      <div className="progress-track">
        <div className="progress-fill" style={{width: `${(step/total)*100}%`}}/>
      </div>
      <span className="progress-count">{step}/{total}</span>
    </div>
  );
};

// === BenefitCard — Auxílio Brasil styled ===
// Always shows max value (R$ 6.484). Status starts "Em análise", finishes "Semi-aprovado".
const STAGE_LABELS = {
  pregnant: { label: 'Gestante' },
  born:     { label: 'Mãe' },
};
const WHEN_LABELS = {
  lt6_p:    { label: 'Início gestação' },
  gte6_p:   { label: 'Reta final' },
  lt30d_b:  { label: 'Recém-nascido' },
  lt6_b:    { label: 'Até 6 meses' },
  mid_b:    { label: 'Até 5 anos' },
  gt5_b:    { label: '5+ anos' },
};
const WORK_LABELS = {
  clt: { label: 'CLT' },
  dom: { label: 'Doméstica' },
  mei: { label: 'MEI' },
  aut: { label: 'Autônoma' },
  cas: { label: 'Do lar' },
  des: { label: 'Desempregada' },
};
const INSS_LABELS = {
  now: { label: 'INSS em dia' },
  lt1: { label: 'INSS recente' },
  gt1: { label: 'INSS antigo' },
  no:  { label: 'Sem INSS' },
};

function BenefitCard({ answers, name, step, finalAmount, isFinal }) {
  const [bumping, setBumping] = React.useState(false);
  const prevStr = React.useRef('');

  React.useEffect(() => {
    const cur = JSON.stringify({ answers, name, isFinal });
    if (prevStr.current && prevStr.current !== cur) {
      setBumping(true);
      const t = setTimeout(() => setBumping(false), 600);
      return () => clearTimeout(t);
    }
    prevStr.current = cur;
  }, [answers, name, isFinal]);

  const stage = answers.stage ? STAGE_LABELS[answers.stage] : null;
  const whenKey = answers.when && answers.stage ? `${answers.when}_${answers.stage === 'pregnant' ? 'p' : 'b'}` : null;
  const when = whenKey ? WHEN_LABELS[whenKey] : null;
  const work = answers.work ? WORK_LABELS[answers.work] : null;
  const inss = answers.inss ? INSS_LABELS[answers.inss] : null;

  const tags = [];
  if (stage) tags.push({ key: 'stage', label: stage.label });
  if (when) tags.push({ key: 'when', label: when.label });
  if (work) tags.push({ key: 'work', label: work.label });
  if (inss) tags.push({ key: 'inss', label: inss.label });

  const displayName = (name || '').trim().toUpperCase() || null;

  // NIS-style number reveals progressively
  const seg1 = step >= 1 ? '1234' : '••••';
  const seg2 = step >= 2 ? '5678' : '••••';
  const seg3 = step >= 3 ? '9012' : '••••';
  const seg4 = isFinal ? '3456' : (step >= 4 ? '34••' : '••••');

  // Status: "Em análise" → "Semi-aprovado"
  const status = isFinal
    ? { label: 'Semi-aprovado', tone: 'final' }
    : { label: 'Em análise', tone: 'analysis' };

  return (
    <div className="benefit-card-wrap">
      <div className={`benefit-card${bumping ? ' bump' : ''}${isFinal ? ' final' : ''}`}>
        {/* Decorative wave (Auxílio Brasil-inspired) */}
        <svg className="bc-wave" viewBox="0 0 380 200" preserveAspectRatio="none">
          <path d="M0,140 Q95,90 190,130 T380,110 L380,200 L0,200 Z" fill="rgba(255,255,255,0.04)"/>
          <path d="M0,160 Q95,110 190,150 T380,130 L380,200 L0,200 Z" fill="rgba(255,255,255,0.03)"/>
        </svg>

        {/* Top: brand row */}
        <div className="bc-top">
          <div className="bc-brand-block">
            <span className="bc-pre">Garanteprev</span>
            <span className="bc-pre-sub">Previdência social</span>
          </div>
          <span className={`bc-status bc-status--${status.tone}`}>
            <span className="bc-status-dot"/>
            {status.label}
          </span>
        </div>

        {/* Big wordmark — Auxílio Brasil style with gold underline */}
        <div className="bc-wordmark">
          <span className="bc-wordmark-1">SALÁRIO</span>
          <span className="bc-wordmark-2">
            <span className="bc-stripe"/>
            <span className="bc-wordmark-text">MATERNIDADE</span>
          </span>
        </div>

        {/* Value row */}
        <div className="bc-value-row">
          <div className="bc-chip">
            <div className="bc-chip-inner"/>
          </div>
          <div className="bc-value-block">
            <div className="bc-value-label">Valor estimado</div>
            <div className="bc-value">
              até R$ <span className="bc-value-num">6.484</span>
            </div>
          </div>
        </div>

        {/* Tags */}
        <div className="bc-tags">
          {tags.length === 0 ? (
            <span className="bc-tag empty">aguardando suas respostas</span>
          ) : tags.map(t => (
            <span key={t.key} className="bc-tag">{t.label}</span>
          ))}
        </div>

        {/* Bottom: titular + number */}
        <div className="bc-bottom">
          <div className="bc-titular-wrap">
            <div className="bc-titular-label">Titular</div>
            <div className="bc-name">
              {displayName || <span className="placeholder">Seu nome aqui</span>}
            </div>
          </div>
          <div className="bc-num-wrap">
            <span className="bc-num-label">NIS</span>
            <span className="bc-num">{seg1}.{seg2}.{seg3}-{seg4}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// Option card
const OptionCard = ({ icon, title, sub, onClick, selected, tapped }) => (
  <button className={`opt-card${selected ? ' selected' : ''}${tapped ? ' tapped' : ''}`} onClick={onClick}>
    {icon && <span className="icon-wrap"><Icon name={icon} size={20}/></span>}
    <span className="opt-body">
      <span className="opt-title">{title}</span>
      {sub && <span className="opt-sub">{sub}</span>}
    </span>
    <Icon name="chev-right" size={16} stroke={2} className="chev"/>
  </button>
);

const TrustStrip = ({ text = "Seus dados são protegidos · LGPD" }) => (
  <div className="trust-strip">
    <Icon name="lock" size={11} stroke={2}/>
    <span>{text}</span>
  </div>
);

const fmtBRL = (n) => 'R$ ' + n.toLocaleString('pt-BR');

// Prefixo +55 é fixo na UI. maskPhone sempre tira 55 do começo se presente,
// já que DDD 55 não existe no Brasil.
const maskPhone = (v) => {
  let d = (v || '').replace(/\D/g, '');
  if (d.startsWith('55') && d.length >= 11) d = d.slice(2);
  d = d.slice(0, 11);
  if (!d) return '';
  if (d.length <= 2) return `(${d}`;
  if (d.length <= 3) return `(${d.slice(0,2)}) ${d.slice(2)}`;
  if (d.length <= 7) return `(${d.slice(0,2)}) ${d.slice(2,3)} ${d.slice(3)}`;
  return `(${d.slice(0,2)}) ${d.slice(2,3)} ${d.slice(3,7)}-${d.slice(7)}`;
};

Object.assign(window, {
  Icon, StatusBar, LogoMark, TopChrome, BenefitCard,
  OptionCard, TrustStrip,
  fmtBRL, maskPhone,
});
