// mockups/taxes-intake.jsx — Taxes module · MATCHES the real product design from index.html
//
// Layout (1280×720 with iPhone on right):
//   - AppHeader top (54px)
//   - case-top: crumbs + big name "TOMÁS SMITH" + status anim + "Send to client" button
//   - 2-column case-grid:
//       LEFT (450px):
//         - Sophia card (avatar photo + description)
//         - Drop zone with 4 flying docs animation
//         - Tile list (appears after docs land)
//         - Case context box (TOMÁS SMITH · Individual taxpayer · TAX_YEAR_2026)
//       RIGHT (530px):
//         - Intake PDF: EasyPro Plus branded header
//         - 5 sections (Personal, W-2, 1099-NEC, 1095-A, Documents on file)
//         - Footer
//   - Floating Sophia detection card (bottom right): "1099-K missing..."
//
// Props:
//   docs            : array of {id, name, fly: 0..1, settled}
//   fieldFills      : map of fieldKey → 0..1
//   docChecks       : map of docKey → boolean
//   sophiaPulse     : 0..1 (legacy — unused in new design)
//   caseStatus      : 'received' | 'analyzing' | 'extracting' | 'ready'
//   showDetection   : boolean — show Sophia detected toast
//
// Exports on window: TaxesIntake, TAXES_DOCS, TAXES_FIELDS

// ── Document catalog (4 docs, matching real product) ────────────────
const TAXES_DOCS = [
  { id: 'w2',    name: 'w2_hilton.pdf',           title: 'FORM W-2',          tagSection: 's2', color: '#007AFF' },
  { id: '1099',  name: '1099_doordash.pdf',       title: 'FORM 1099-NEC',     tagSection: 's3', color: '#FF9500' },
  { id: 'id',    name: 'id_license.jpg',          title: 'TX DRIVER LICENSE', tagSection: 's1', color: '#34C759' },
  { id: '1095a', name: '1095a_marketplace.pdf',   title: 'FORM 1095-A',       tagSection: 's4', color: '#5AC8FA' },
];

// ── Field catalog organized by section ──────────────────────────────
const TAXES_FIELDS = [
  // Section 1: Personal Information (from ID)
  { key: 's1.name',    section: 's1', label: 'Legal Name',         value: 'TOMÁS SMITH',                       sourceDoc: 'id' },
  { key: 's1.ssn',     section: 's1', label: 'SSN',                value: 'XXX-XX-4218',                       sourceDoc: 'id' },
  { key: 's1.marital', section: 's1', label: 'Marital status',     value: 'Married',                           sourceDoc: 'id' },
  { key: 's1.addr',    section: 's1', label: 'Address',            value: '8810 Commodity Cir, Orlando, FL 32819', sourceDoc: 'id' },
  // Section 2: W-2 Wages (Hilton)
  { key: 's2.employer',  section: 's2', label: 'Employer',                  value: 'HILTON WORLDWIDE', sourceDoc: 'w2' },
  { key: 's2.gross',     section: 's2', label: 'Gross wages (Box 1)',       value: '$64,820.00',       sourceDoc: 'w2' },
  { key: 's2.fed',       section: 's2', label: 'Federal withheld (Box 2)',  value: '$8,914.20',        sourceDoc: 'w2' },
  // Section 3: 1099-NEC
  { key: 's3.payer', section: 's3', label: 'Payer',                    value: 'DOORDASH INC', sourceDoc: '1099' },
  { key: 's3.nec',   section: 's3', label: 'Nonemployee compensation', value: '$18,420.00',   sourceDoc: '1099' },
  // Section 4: 1095-A
  { key: 's4.mkt',  section: 's4', label: 'Marketplace',            value: 'HealthCare.gov', sourceDoc: '1095a' },
  { key: 's4.aptc', section: 's4', label: 'APTC received (annual)', value: '$3,420.00',      sourceDoc: '1095a' },
];

// ── Status phase config ─────────────────────────────────────────────
const STATUS_PHASES = {
  received: {
    color: '#007AFF', bg: 'transparent',
    label: '4 documentos recibidos',
    icon: (
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 16v3a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-3M7 10l5 5 5-5M12 15V3"/>
      </svg>
    ),
  },
  analyzing: {
    color: '#7c3aed', bg: 'rgba(139,92,246,0.08)',
    label: 'Sophia analizando 4 archivos…',
    icon: <PurplePulse />,
  },
  extracting: {
    color: '#7c3aed', bg: 'rgba(139,92,246,0.08)',
    label: 'Llenando Intake Fiscal…',  // overridden at render time via lang lookup
    icon: <PurplePulse />,
  },
  ready: {
    color: '#0aa674', bg: 'rgba(10,166,116,0.10)',
    label: 'Listo para revisar',
    icon: (
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="20 6 9 17 4 12"/>
      </svg>
    ),
  },
};

function PurplePulse() {
  return (
    <span style={{
      display: 'inline-block',
      width: 8, height: 8,
      borderRadius: '50%',
      background: 'radial-gradient(circle at 35% 35%, #c6a7ff, #7a3cff 60%)',
      boxShadow: '0 0 6px rgba(155, 77, 255, 0.6)',
      animation: 'sol-pulse-small 1.6s ease-in-out infinite',
    }} />
  );
}

// ─────────────────────────────────────────────────────────────────────
function TaxesIntake({
  docs = [],
  fieldFills = {},
  docChecks = {},
  caseStatus = 'received',
  showDetection = false,
}) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ix = i18n.intake || {};
  const sh = i18n.shell || {};
  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: '#fafafa',
      overflow: 'hidden',
    }}>
      <AppHeader
        moduleName="Taxes"
        moduleAccent="#007AFF"
        moduleIcon="🧮"
        breadcrumbs={[]}
      />

      {/* ── case-top: crumbs + name + status + Send to client ────── */}
      <div style={{
        position: 'absolute',
        top: 64, left: 22, right: 22,
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'flex-start',
          justifyContent: 'space-between',
          gap: 16,
          marginBottom: 8,
        }}>
          <div>
            <div style={{
              fontFamily: 'ui-monospace, "SF Mono", monospace',
              fontSize: 10.5,
              color: '#6e6e73',
              letterSpacing: 0.02,
              marginBottom: 4,
            }}>
              {lang === 'en' ? 'Clients / Tomás Smith / Tax Intake 2026' : 'Clientes / Tomás Smith / Intake Fiscal 2026'}
            </div>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: 14,
            }}>
              <h3 style={{
                fontSize: 22,
                fontWeight: 600,
                letterSpacing: -0.02,
                color: '#1d1d1f',
                margin: 0,
                lineHeight: 1,
              }}>Tomás Smith</h3>
              <StatusPill phase={caseStatus} />
            </div>
          </div>

          <button style={{
            background: '#007AFF',
            color: '#fff',
            border: 0,
            borderRadius: 999,
            padding: '8px 16px',
            fontSize: 12,
            fontWeight: 500,
            letterSpacing: -0.005,
            display: 'inline-flex',
            alignItems: 'center',
            gap: 6,
            boxShadow: '0 4px 14px rgba(0, 122, 255, 0.25)',
            cursor: 'pointer',
            flexShrink: 0,
          }}>
            {sh.btn_send_client || 'Enviar al cliente'}
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
              <path d="M5 12h14M13 5l7 7-7 7"/>
            </svg>
          </button>
        </div>
      </div>

      {/* ── 2-column case-grid ─────────────────────────────────── */}
      <div style={{
        position: 'absolute',
        top: 128, left: 22, right: 22, bottom: 20,
        display: 'grid',
        gridTemplateColumns: '440px 1fr',
        gap: 16,
      }}>
        {/* LEFT — Sophia card + drop zone + case context */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <DropzoneCard docs={docs} />
          <CaseContextCard />
        </div>

        {/* RIGHT — Intake PDF */}
        <IntakePDF fieldFills={fieldFills} docChecks={docChecks} />
      </div>

      {/* ── Sophia detected — floating card bottom right ─────────── */}
      {showDetection && <SophiaDetectionCard />}

      <style>{`
        @keyframes sol-pulse-small {
          0%, 100% { transform: scale(1); opacity: 1; }
          50%      { transform: scale(1.2); opacity: 0.6; }
        }
        @keyframes sol-cellFlash {
          0%   { background: rgba(0, 122, 255, 0); }
          30%  { background: rgba(0, 122, 255, 0.10); }
          100% { background: rgba(0, 122, 255, 0); }
        }
      `}</style>
    </div>
  );
}

// ── Status pill (4 phases, cross-fading) ─────────────────────────────
function StatusPill({ phase }) {
  const lang = useTimeline().lang || 'es';
  const cfg = STATUS_PHASES[phase] || STATUS_PHASES.received;
  // i18n overrides for the 4 phases — keyed by phase name
  const phaseEN = {
    received: 'Documents received',
    extracting: 'Filling Tax Intake…',
    ready: 'Intake ready · ready to sign',
    signed: 'Signed · queued',
  };
  const label = lang === 'en' ? (phaseEN[phase] || cfg.label) : cfg.label;
  return (
    <div style={{
      position: 'relative',
      display: 'inline-flex',
      alignItems: 'center',
      gap: 6,
      padding: '4px 10px',
      borderRadius: 999,
      background: cfg.bg,
      border: cfg.bg === 'transparent' ? '1px solid #e8e8ed' : 'none',
      color: cfg.color,
      fontSize: 11.5,
      fontWeight: 500,
      letterSpacing: -0.005,
      whiteSpace: 'nowrap',
      transition: 'background 240ms, color 240ms',
    }}>
      {cfg.icon}
      <span>{label}</span>
    </div>
  );
}

// ── Sophia drop zone card ────────────────────────────────────────────
function DropzoneCard({ docs }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ix = i18n.intake || {};
  const settledCount = docs.filter(d => d.settled).length;
  const anyFlying = docs.some(d => d.fly > 0 && d.fly < 1);
  const allSettled = settledCount === TAXES_DOCS.length;

  return (
    <div style={{
      background: '#fff',
      border: '1px solid #e8e8ed',
      borderRadius: 14,
      padding: 14,
      boxShadow: '0 1px 3px rgba(0,0,0,0.03)',
    }}>
      {/* Head: avatar + name + role */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 10,
        marginBottom: 10,
      }}>
        <div style={{
          position: 'relative',
          width: 36, height: 36,
          borderRadius: '50%',
          overflow: 'hidden',
          border: '1.5px solid #8b5cf6',
          boxShadow: '0 2px 6px rgba(139, 92, 246, 0.25)',
          flexShrink: 0,
        }}>
          <img
            src="../static/avatar_sophia/sophia_v1_outfit_01_neutra.jpg"
            alt="Sophia"
            style={{
              width: '100%', height: '100%',
              objectFit: 'cover',
              objectPosition: '50% 15%',
              display: 'block',
            }}
            onError={(e) => {
              // Fallback if path doesn't resolve
              e.target.style.display = 'none';
              e.target.parentElement.style.background = 'radial-gradient(circle at 35% 30%, #c4b5fd, #8b5cf6)';
            }}
          />
          {/* Green dot */}
          <div style={{
            position: 'absolute',
            bottom: 0, right: 0,
            width: 9, height: 9,
            background: '#34C759',
            borderRadius: '50%',
            border: '1.5px solid #fff',
          }} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <b style={{
            fontSize: 13.5,
            fontWeight: 600,
            color: '#1d1d1f',
            letterSpacing: -0.01,
          }}>Sophia</b>
          <span style={{
            fontSize: 11,
            color: '#6e6e73',
          }}>{ix.sophia_role || 'Asistente IA · EasyPro'}</span>
        </div>
      </div>

      {/* Description */}
      <p style={{
        fontSize: 11.5,
        lineHeight: 1.5,
        color: '#6e6e73',
        margin: '0 0 12px',
        letterSpacing: -0.005,
      }}>
        {(() => {
          const tmpl = ix.sophia_drop_copy || 'Sophia detecta automáticamente: dropea {DOCS}, etc. Yo extraigo todo y lo pongo en la sección correcta del intake.';
          const [before, after] = tmpl.split('{DOCS}');
          return <>{before}<b style={{ color: '#1d1d1f', fontWeight: 600 }}>W-2s, 1099s, IDs, 1095-A</b>{after}</>;
        })()}
      </p>

      {/* Drop zone */}
      <div style={{
        position: 'relative',
        background: anyFlying ? 'rgba(0, 122, 255, 0.04)' : '#fafafa',
        border: `2px dashed ${anyFlying ? '#007AFF' : '#d2d2d7'}`,
        borderRadius: 10,
        minHeight: 130,
        padding: 16,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 4,
        transition: 'background 200ms, border-color 200ms',
        overflow: 'hidden',
        marginBottom: allSettled ? 10 : 0,
      }}>
        {/* Empty state inside */}
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#007AFF" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 19V5M5 12l7-7 7 7"/>
        </svg>
        <b style={{
          fontSize: 13.5,
          fontWeight: 600,
          color: '#1d1d1f',
          letterSpacing: -0.01,
          marginTop: 2,
        }}>{ix.drop_main || 'Arrastra archivos aquí'}</b>
        <span style={{
          fontSize: 11,
          color: '#6e6e73',
        }}>{ix.drop_sub || 'o click para seleccionar'}</span>

        {/* Flying docs animation */}
        {docs.map((doc, i) => (
          <FlyingDoc key={doc.id} doc={doc} order={i} />
        ))}
      </div>

      {/* Settled tiles list */}
      {settledCount > 0 && (
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          gap: 4,
          marginTop: 10,
        }}>
          {docs.map(doc => doc.settled && (
            <DocTile key={doc.id} name={doc.name} />
          ))}
        </div>
      )}
    </div>
  );
}

// ── Flying doc (during fly animation, inside drop zone) ─────────────
function FlyingDoc({ doc, order }) {
  // Visible only during fly (0 < fly < 1.05)
  const p = doc.fly || 0;
  if (p <= 0 || p >= 1.0) return null;

  const e = Easing.easeOutCubic(p);
  // Source = above the drop zone (top right corner)
  const srcX = 280 + order * 14;
  const srcY = -160 - order * 8;
  // Target = center of drop zone
  const tgtX = 90 + (order - 1.5) * 30; // small spread
  const tgtY = 30 + (order % 2) * 10;
  const x = srcX + (tgtX - srcX) * e;
  const y = srcY + (tgtY - srcY) * e;
  const rot = (1 - e) * 18 + ((order % 2 === 0 ? -8 : 8)) * e;
  const scale = 0.6 + 0.4 * e;
  const opacity = Math.min(1, p * 2);

  const docMeta = TAXES_DOCS.find(d => d.id === doc.id);
  const isImage = doc.name.endsWith('.jpg') || doc.name.endsWith('.png');

  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width: 110, height: 70,
      background: '#fff',
      borderRadius: 6,
      borderTop: `4px solid ${docMeta?.color || '#007AFF'}`,
      border: `1px solid ${docMeta?.color || '#007AFF'}55`,
      boxShadow: `0 ${4 + 10 * e}px ${10 + 14 * e}px rgba(0,0,0,${0.08 + 0.04 * e})`,
      transform: `rotate(${rot}deg) scale(${scale})`,
      transformOrigin: 'center',
      opacity,
      padding: '10px 6px 6px',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      textAlign: 'center',
      pointerEvents: 'none',
      zIndex: 10,
      willChange: 'transform, opacity',
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={docMeta?.color || '#007AFF'} strokeWidth="1.6">
        {isImage ? (
          <>
            <rect x="3" y="4" width="18" height="16" rx="2"/>
            <circle cx="9" cy="11" r="2"/>
            <path d="M14 10h4M14 14h4M5 17h6"/>
          </>
        ) : (
          <>
            <rect x="3" y="4" width="18" height="16"/>
            <path d="M3 9h18M9 4v16M15 4v16"/>
          </>
        )}
      </svg>
      <div style={{
        fontSize: 8.5,
        fontWeight: 700,
        color: '#1d1d1f',
        letterSpacing: 0.1,
        marginTop: 2,
      }}>{docMeta?.title || doc.name}</div>
      <div style={{
        fontSize: 8,
        fontFamily: 'ui-monospace, monospace',
        color: '#6e6e73',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        maxWidth: '100%',
      }}>{doc.name}</div>
    </div>
  );
}

// ── Doc tile (settled, after fly completes) ─────────────────────────
function DocTile({ name }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      gap: 8,
      padding: '6px 10px',
      background: '#fafafa',
      borderRadius: 6,
      animation: 'sol-tile-in 240ms ease-out',
    }}>
      <svg width="11" height="13" viewBox="0 0 24 28" fill="none" stroke="#007AFF" strokeWidth="1.6">
        <path d="M3 2h13l5 5v19a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z"/>
      </svg>
      <span style={{
        flex: 1,
        fontSize: 11.5,
        color: '#1d1d1f',
        fontFamily: 'ui-monospace, monospace',
        letterSpacing: -0.005,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
      }}>{name}</span>
      <span style={{
        width: 16, height: 16,
        borderRadius: '50%',
        background: '#34C759',
        color: '#fff',
        fontSize: 10,
        fontWeight: 700,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}>✓</span>
    </div>
  );
}

// ── Case context card ────────────────────────────────────────────────
function CaseContextCard() {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ix = i18n.intake || {};
  return (
    <div style={{
      background: '#fff',
      border: '1px solid #e8e8ed',
      borderRadius: 14,
      padding: 14,
      boxShadow: '0 1px 3px rgba(0,0,0,0.03)',
    }}>
      <div style={{
        fontFamily: 'ui-monospace, "SF Mono", monospace',
        fontSize: 9.5,
        color: '#6e6e73',
        letterSpacing: 0.12,
        textTransform: 'uppercase',
        fontWeight: 600,
        marginBottom: 6,
      }}>{ix.case_context || 'Contexto del caso'}</div>
      <div style={{
        fontSize: 16,
        fontWeight: 600,
        color: '#1d1d1f',
        letterSpacing: -0.015,
        marginBottom: 2,
      }}>TOMÁS SMITH</div>
      <div style={{
        fontSize: 11.5,
        color: '#6e6e73',
        marginBottom: 6,
      }}>{ix.case_role || 'Sponsor · US Citizen · Family-based AOS'}</div>
      <div style={{
        fontSize: 11,
        color: '#1d1d1f',
        fontFamily: 'ui-monospace, monospace',
      }}>
        <b style={{ color: '#1d1d1f' }}>{ix.case_package || 'Paquete:'}</b> TAX_YEAR_2026
      </div>
    </div>
  );
}

// ── Intake PDF (right column) ────────────────────────────────────────
function IntakePDF({ fieldFills, docChecks }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ix = i18n.intake || {};
  const fillOf = (key) => Math.min(1, Math.max(0, fieldFills[key] || 0));

  return (
    <div style={{
      background: '#fff',
      border: '1px solid #d2d2d7',
      borderRadius: 14,
      padding: 14,
      boxShadow: '0 4px 16px rgba(0,0,0,0.05)',
      overflow: 'hidden',
      display: 'flex',
      flexDirection: 'column',
      minHeight: 0,
    }}>
      {/* Branded header */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: '1fr auto',
        alignItems: 'center',
        padding: '0 0 10px',
        borderBottom: '2px solid #007AFF',
        marginBottom: 10,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 30, height: 30,
            borderRadius: 7,
            background: 'linear-gradient(135deg, #007AFF, #5a6dff, #8b5cf6)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#fff',
            fontWeight: 700,
            fontSize: 13,
            letterSpacing: -0.04,
          }}>EP</div>
          <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15 }}>
            <b style={{ fontSize: 13, fontWeight: 600, color: '#1d1d1f', letterSpacing: -0.01 }}>EasyPro Plus</b>
            <span style={{ fontSize: 10.5, color: '#6e6e73' }}>{ix.intake_label || 'Intake Fiscal · Año 2026'}</span>
          </div>
        </div>
        <div style={{
          textAlign: 'right',
          fontSize: 9.5,
          color: '#6e6e73',
          lineHeight: 1.5,
          fontFamily: 'ui-monospace, monospace',
        }}>
          <div>{ix.client_label || 'Cliente:'} Tomás Smith</div>
          <div>{ix.preparer_label || 'Preparador:'} Amelia · EasyPro</div>
        </div>
      </div>

      {/* Sections */}
      <div style={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        gap: 5,
        minHeight: 0,
      }}>
        <IntakeSection num={1} title={ix.sec1_title || 'Información Personal'}>
          <IntakeField n={1} label={ix.f_name || "Nombre legal"}   field="s1.name"    fillP={fillOf('s1.name')} />
          <IntakeField n={2} label="SSN"            field="s1.ssn"     fillP={fillOf('s1.ssn')} />
          <IntakeField n={3} label={ix.f_marital || "Estado civil"}   field="s1.marital" fillP={fillOf('s1.marital')} />
          <IntakeField n={4} label={ix.f_addr || "Dirección"}      field="s1.addr"    fillP={fillOf('s1.addr')} />
        </IntakeSection>

        <IntakeSection num={2} title={ix.sec2_title || 'Ingresos W-2 (Hilton)'}>
          <IntakeField n={1} label={ix.f_employer || "Empleador"}              field="s2.employer" fillP={fillOf('s2.employer')} />
          <IntakeField n={2} label={ix.f_gross || "Salarios brutos (Box 1)"} field="s2.gross"   fillP={fillOf('s2.gross')} />
          <IntakeField n={3} label={ix.f_fed || "Federal retenido (Box 2)"} field="s2.fed"   fillP={fillOf('s2.fed')} />
        </IntakeSection>

        <IntakeSection num={3} title={ix.sec3_title || '1099-NEC · Trabajo Independiente'}>
          <IntakeField n={1} label={ix.f_payer || "Pagador"}                  field="s3.payer" fillP={fillOf('s3.payer')} />
          <IntakeField n={2} label={ix.f_nec || "Compensación no-empleado"} field="s3.nec"   fillP={fillOf('s3.nec')} />
        </IntakeSection>

        <IntakeSection num={4} title={ix.sec4_title || '1095-A · Seguro Médico (ACA)'}>
          <IntakeField n={1} label={ix.f_mkt || "Mercado"}           field="s4.mkt"  fillP={fillOf('s4.mkt')} />
          <IntakeField n={2} label={ix.f_aptc || "APTC recibido (anual)"} field="s4.aptc" fillP={fillOf('s4.aptc')} />
        </IntakeSection>

        <IntakeSection num={5} title={ix.sec5_title || 'Documentos en archivo'}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: '3px 12px',
            padding: '4px 12px 4px 8px',
            fontSize: 11,
          }}>
            <DocCheckbox checked={!!docChecks.w2}    label="W-2 · Hilton Worldwide" />
            <DocCheckbox checked={!!docChecks['1099']} label="1099-NEC · DoorDash Inc" />
            <DocCheckbox checked={!!docChecks.id}    label="TX Driver License" />
            <DocCheckbox checked={!!docChecks['1095a']} label="1095-A · HealthCare.gov" />
          </div>
        </IntakeSection>
      </div>

      {/* Footer */}
      <div style={{
        marginTop: 8,
        paddingTop: 6,
        borderTop: '1px solid #e8e8ed',
        fontSize: 9,
        color: '#a1a1a6',
        textAlign: 'center',
        fontFamily: 'ui-monospace, monospace',
        letterSpacing: 0.04,
      }}>{ix.footer || 'EasyPro Plus · Intake Fiscal · Uso exclusivo del preparador autorizado'}</div>
    </div>
  );
}

function IntakeSection({ num, title, children }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ix = i18n.intake || {};
  return (
    <div style={{
      border: '1px solid #e2e2e7',
      borderRadius: 8,
      flexShrink: 0,
    }}>
      <div style={{
        background: '#f0f7ff',
        color: '#007AFF',
        padding: '4px 12px',
        fontSize: 11,
        fontWeight: 500,
        letterSpacing: 0.01,
        display: 'flex',
        alignItems: 'center',
        gap: 4,
      }}>
        <span style={{ fontWeight: 700 }}>►</span>
        <span>{(ix.section_prefix || 'Sección')} {num}. {title}</span>
      </div>
      {children}
    </div>
  );
}

function IntakeField({ n, label, fillP }) {
  const full = TAXES_FIELDS.find(f => f.label === label || f.key.endsWith(label.toLowerCase()));
  // Find the field by inferring from label — fallback to "—"
  // Better: rely on fillP and look up the value from the closest matching field

  // We need to display the value text. The IntakeField is called per row;
  // map label to value via a helper:
  const valueMap = {
    // ES labels
    'Nombre legal': 'TOMÁS SMITH',
    'SSN': 'XXX-XX-4218',
    'Estado civil': 'Married',
    'Dirección': '8810 Commodity Cir, Orlando, FL 32819',
    'Empleador': 'HILTON WORLDWIDE',
    'Salarios brutos (Box 1)': '$64,820.00',
    'Federal retenido (Box 2)': '$8,914.20',
    'Pagador': 'DOORDASH INC',
    'Compensación no-empleado': '$18,420.00',
    'Mercado': 'HealthCare.gov',
    'APTC recibido (anual)': '$3,420.00',
    // EN labels (same values)
    'Legal name': 'TOMÁS SMITH',
    'Marital status': 'Married',
    'Address': '8810 Commodity Cir, Orlando, FL 32819',
    'Employer': 'HILTON WORLDWIDE',
    'Gross wages (Box 1)': '$64,820.00',
    'Federal withheld (Box 2)': '$8,914.20',
    'Payer': 'DOORDASH INC',
    'Non-employee compensation': '$18,420.00',
    'Marketplace': 'HealthCare.gov',
    'APTC received (annual)': '$3,420.00',
  };
  const value = valueMap[label] || '—';
  const visibleLen = Math.floor(value.length * fillP);
  const visible = value.slice(0, visibleLen);
  const isFilling = fillP > 0 && fillP < 1;
  const isDone = fillP >= 1;

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '22px 1fr auto',
      gap: 6,
      padding: '4px 12px 4px 8px',
      borderTop: n > 1 ? '1px solid #f5f5f7' : 'none',
      fontSize: 10.5,
      alignItems: 'baseline',
    }}>
      <span style={{
        fontWeight: 600,
        color: '#6e6e73',
        fontFamily: 'ui-monospace, monospace',
      }}>{n}.</span>
      <span style={{
        color: '#1d1d1f',
        letterSpacing: -0.005,
      }}>{label}</span>
      <span style={{
        fontFamily: 'ui-monospace, monospace',
        color: isDone ? '#1d1d1f' : (isFilling ? '#007AFF' : '#c7c7cf'),
        fontWeight: isDone ? 600 : 400,
        textAlign: 'right',
        whiteSpace: 'nowrap',
        background: isFilling ? 'rgba(0, 122, 255, 0.08)' : 'transparent',
        padding: '1px 4px',
        borderRadius: 3,
        transition: 'background 240ms',
      }}>
        {visible || (fillP === 0 ? '—' : '')}
        {isFilling && (
          <span style={{
            display: 'inline-block',
            width: 1, height: 10,
            background: '#007AFF',
            marginLeft: 1,
            verticalAlign: 'middle',
            animation: 'sol-caret 0.6s steps(1) infinite',
          }} />
        )}
      </span>
    </div>
  );
}

function DocCheckbox({ checked, label }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      gap: 6,
      fontSize: 10.5,
      color: '#1d1d1f',
    }}>
      <span style={{
        width: 13, height: 13,
        background: checked ? '#34C759' : '#fff',
        border: `1.5px solid ${checked ? '#34C759' : '#c7c7cf'}`,
        borderRadius: 3,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#fff',
        fontSize: 9,
        fontWeight: 700,
        flexShrink: 0,
        transition: 'all 180ms',
      }}>{checked ? '✓' : ''}</span>
      <span style={{ letterSpacing: -0.005, color: checked ? '#1d1d1f' : '#a1a1a6' }}>{label}</span>
    </div>
  );
}

// ── Sophia detection floating card ───────────────────────────────────
function SophiaDetectionCard() {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ix = i18n.intake || {};
  return (
    <div style={{
      position: 'absolute',
      bottom: 20, right: 22,
      width: 260,
      background: 'linear-gradient(160deg, #1a1340 0%, #2a1a6a 50%, #3a1f8a 100%)',
      color: '#fff',
      borderRadius: 14,
      padding: '10px 12px',
      boxShadow: '0 18px 40px -16px rgba(122, 60, 255, 0.55), 0 8px 18px -8px rgba(0,0,0,0.40)',
      border: '1px solid rgba(155, 77, 255, 0.36)',
      fontSize: 11.5,
      zIndex: 12,
      animation: 'sol-sophia-toast-in 380ms ease-out',
    }}>
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        marginBottom: 6,
      }}>
        <div style={{
          width: 14, height: 14,
          borderRadius: '50%',
          background: 'radial-gradient(circle at 35% 35%, #c6a7ff, #7a3cff 60%, #3a1f8a)',
          boxShadow: '0 0 0 2px rgba(155, 77, 255, 0.2), 0 0 6px rgba(155, 77, 255, 0.55)',
          flexShrink: 0,
          position: 'relative',
        }}>
          <div style={{
            position: 'absolute',
            inset: -4,
            borderRadius: '50%',
            border: '1px solid rgba(155, 77, 255, 0.4)',
            animation: 'sol-sophia-pulse 2.5s ease-out infinite',
          }} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15, minWidth: 0, flex: 1 }}>
          <div style={{
            fontSize: 11,
            fontWeight: 600,
            letterSpacing: -0.005,
            color: '#fff',
          }}>{ix.toast_detected || 'Sophia detectó'}</div>
          <div style={{
            fontSize: 9.5,
            color: 'rgba(255,255,255,0.55)',
            fontFamily: 'ui-monospace, monospace',
            letterSpacing: 0.02,
          }}>{ix.toast_just_now || 'justo ahora'}</div>
        </div>
      </div>
      <div style={{
        fontSize: 11,
        lineHeight: 1.4,
        color: 'rgba(255,255,255,0.88)',
        margin: '0 0 8px',
      }}>
        {(() => {
          const tmpl = ix.toast_body || 'Falta 1099-K. Pagos de PayPal por $3,420 no reportados en el intake.';
          const parts = tmpl.split(/(Falta 1099-K\.|Missing 1099-K\.)/);
          return parts.map((p, i) =>
            /Falta 1099-K\.|Missing 1099-K\./.test(p)
              ? <b key={i} style={{ color: '#fff', fontWeight: 600 }}>{p}</b>
              : p
          );
        })()}
      </div>
      <div style={{ display: 'flex', gap: 6 }}>
        <button style={{
          flex: 1,
          padding: '5px 11px',
          borderRadius: 999,
          background: '#fff',
          color: '#7c3aed',
          border: '1px solid #fff',
          fontSize: 10.5,
          fontWeight: 500,
          cursor: 'pointer',
        }}>{ix.toast_btn || 'Revisar mensaje'}</button>
        <button style={{
          width: 30, padding: '4px 6px',
          borderRadius: 999,
          background: 'rgba(255,255,255,0.08)',
          border: '1px solid rgba(255,255,255,0.18)',
          color: '#fff',
          fontSize: 13,
          lineHeight: 1,
          cursor: 'pointer',
        }}>×</button>
      </div>
    </div>
  );
}

// Animations
if (typeof document !== 'undefined' && !document.getElementById('sol-taxes-anim')) {
  const s = document.createElement('style');
  s.id = 'sol-taxes-anim';
  s.textContent = `
    @keyframes sol-tile-in {
      from { opacity: 0; transform: translateX(-8px); }
      to   { opacity: 1; transform: translateX(0); }
    }
    @keyframes sol-sophia-toast-in {
      from { opacity: 0; transform: translateY(20px) scale(0.96); }
      to   { opacity: 1; transform: translateY(0) scale(1); }
    }
    @keyframes sol-sophia-pulse {
      0%   { transform: scale(0.9); opacity: 0.9; }
      100% { transform: scale(1.5); opacity: 0; }
    }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { TaxesIntake, TAXES_DOCS, TAXES_FIELDS });
