// Entity Structure Quiz — interactive educational tool
const { useState: useStateQuiz, useMemo: useMemoQuiz, useEffect: useEffectQuiz } = React;

/* --- Entity catalog ---------------------------------------------------- */
const ENTITIES = {
  sole: {
    key: 'sole',
    name: 'Sole Proprietor',
    nameEm: 'Sole Proprietor',
    tagline: 'The default for a one-person show with nothing on the line but time.',
    incorporation: { value: 'No', kind: 'no', note: 'No state filing; operate under your own name or a DBA.' },
    liability: { value: 'None', kind: 'no', note: 'You and the business are the same person, legally and financially.' },
    passthrough: { value: 'Yes', kind: 'yes', note: 'All profit flows to your personal return.' },
    form: { value: 'Schedule C', note: 'Filed with your 1040.' },
    deadline: { value: 'Apr 15', note: 'With your personal return (Oct 15 on extension).' },
    bestFor: 'Freelancers and side-hustles testing an idea with no employees, no inventory, and no outside capital.',
  },
  partnership: {
    key: 'partnership',
    name: 'General Partnership',
    nameEm: 'Partnership',
    tagline: 'Two or more owners, pass-through tax, and shared personal risk.',
    incorporation: { value: 'No', kind: 'no', note: 'No state formation required — but get a written partnership agreement.' },
    liability: { value: 'None', kind: 'no', note: 'Each partner is personally liable for debts and the acts of the others.' },
    passthrough: { value: 'Yes', kind: 'yes', note: 'Profit and loss flow to partners via K-1s.' },
    form: { value: 'Form 1065 + K-1', note: 'Partnership return plus a K-1 to each partner.' },
    deadline: { value: 'Mar 15', note: 'Sep 15 on extension.' },
    bestFor: 'A temporary or low-risk venture between trusted co-owners where formalizing as an LLC isn\'t worth the filing yet.',
  },
  llc: {
    key: 'llc',
    name: 'LLC',
    nameEm: 'LLC',
    tagline: 'Liability protection with pass-through simplicity. The workhorse for small business.',
    incorporation: { value: 'Yes', kind: 'yes', note: 'File articles of organization with the state; maintain an operating agreement.' },
    liability: { value: 'Yes', kind: 'yes', note: 'Members generally aren\'t personally liable for business debts.' },
    passthrough: { value: 'Yes', kind: 'yes', note: 'Default tax treatment is pass-through (Sch. C, 1065, or S-corp if elected).' },
    form: { value: 'Sch. C / 1065', note: 'Sch. C for single-member; 1065 for multi-member; 1120-S if S-corp elected.' },
    deadline: { value: 'Apr 15 / Mar 15', note: 'Apr 15 single-member; Mar 15 multi-member or S-elected.' },
    bestFor: 'Most owner-operated small businesses that want liability protection without the formalities of a corporation.',
  },
  scorp: {
    key: 'scorp',
    name: 'S-Corporation',
    nameEm: 'S-Corp',
    tagline: 'Pass-through taxation with payroll discipline — a self-employment tax strategy, not a legal form.',
    incorporation: { value: 'Yes', kind: 'yes', note: 'Formed as LLC or C-corp, then elect S status with IRS Form 2553.' },
    liability: { value: 'Yes', kind: 'yes', note: 'Inherited from the underlying LLC or corporation.' },
    passthrough: { value: 'Yes', kind: 'yes', note: 'Income passes to shareholders — but owners must take "reasonable" W-2 salary.' },
    form: { value: 'Form 1120-S + K-1', note: 'S-corp return plus a K-1 to each shareholder.' },
    deadline: { value: 'Mar 15', note: 'Sep 15 on extension.' },
    bestFor: 'Profitable owner-operated businesses clearing ~$60k+ in net profit where self-employment tax savings offset payroll complexity.',
  },
  ccorp: {
    key: 'ccorp',
    name: 'C-Corporation',
    nameEm: 'C-Corp',
    tagline: 'The venture-backable default — clean cap tables, stock options, and institutional capital.',
    incorporation: { value: 'Yes', kind: 'yes', note: 'File articles of incorporation; adopt bylaws; issue stock; hold board meetings.' },
    liability: { value: 'Yes', kind: 'yes', note: 'Shareholders protected; pierce-the-veil rules apply if formalities lapse.' },
    passthrough: { value: 'No', kind: 'no', note: 'Taxed at the entity level (21% federal), then again on dividends.' },
    form: { value: 'Form 1120', note: 'Corporate income tax return.' },
    deadline: { value: 'Apr 15', note: 'Oct 15 on extension. (Fiscal-year filers: 15th of the 4th month after year-end.)' },
    bestFor: 'Startups raising priced venture rounds, issuing stock options, or planning to retain earnings / go public.',
  },
  nonprofit: {
    key: 'nonprofit',
    name: 'Nonprofit Corporation',
    nameEm: 'Nonprofit',
    tagline: 'Mission-driven, tax-exempt, and accountable to a board — not shareholders.',
    incorporation: { value: 'Yes', kind: 'yes', note: 'Incorporate with the state, then apply for 501(c)(3) status with IRS Form 1023.' },
    liability: { value: 'Yes', kind: 'yes', note: 'Directors and officers shielded, subject to fiduciary duties.' },
    passthrough: { value: 'N/A', kind: 'partial', note: 'Generally tax-exempt; no owners to pass income to. UBIT applies to unrelated activities.' },
    form: { value: 'Form 990', note: '990, 990-EZ, or 990-N depending on revenue.' },
    deadline: { value: 'May 15', note: '15th day of the 5th month after fiscal year-end — for calendar-year filers, May 15.' },
    bestFor: 'Charitable, educational, or religious missions funded by grants and donations rather than profit.',
  },
};

/* --- Question bank ----------------------------------------------------- */
/* Each option carries a score map: how strongly it points toward each entity. */
const QUESTIONS = [
  {
    id: 'owners',
    eyebrow: 'Ownership',
    title: 'How many owners will the business have?',
    sub: 'Spouse co-owners count as one or two depending on your state — assume two if you both draw income.',
    options: [
      { id: 'one',   label: 'Just me',           hint: 'Solo founder, freelancer, or single operator.',        scores: { sole: 3, llc: 3, scorp: 2, ccorp: 1 } },
      { id: 'two',   label: 'Two to five',       hint: 'Co-founders, family, or a small partnership.',         scores: { partnership: 2, llc: 3, scorp: 2, ccorp: 2 } },
      { id: 'many',  label: 'Many / investors',  hint: 'You plan to issue equity to outside investors.',       scores: { ccorp: 4, llc: 1 } },
      { id: 'board', label: 'A board + donors',  hint: 'Mission-based, funded by grants and contributions.',    scores: { nonprofit: 5 } },
    ],
  },
  {
    id: 'liability',
    eyebrow: 'Risk',
    title: 'How much personal liability exposure can you live with?',
    sub: 'Think product risk, premises, employees, contracts — anything that could produce a lawsuit.',
    options: [
      { id: 'low',  label: 'Minimal — it\'s a low-risk service',  hint: 'Writing, consulting, digital goods with no physical delivery.',           scores: { sole: 2, partnership: 1, llc: 2 } },
      { id: 'med',  label: 'Some — clients, contracts, vendors',  hint: 'Standard B2B or B2C services with contracts and some financial exposure.', scores: { llc: 3, scorp: 2, ccorp: 2 } },
      { id: 'high', label: 'High — employees, inventory, or product', hint: 'Physical product, staff, a storefront, or regulated activity.',         scores: { llc: 4, scorp: 3, ccorp: 3, nonprofit: 2 } },
    ],
  },
  {
    id: 'capital',
    eyebrow: 'Capital',
    title: 'How will you fund the business?',
    sub: 'This drives the entity more than almost anything else — investors have strong preferences.',
    options: [
      { id: 'self',      label: 'Self-funded or customer revenue', hint: 'Bootstrapped from savings or operating cash.',            scores: { sole: 2, llc: 3, scorp: 2 } },
      { id: 'debt',      label: 'Loans, lines of credit, SBA',     hint: 'Debt financing from banks or the SBA.',                   scores: { llc: 3, scorp: 2, ccorp: 1 } },
      { id: 'angels',    label: 'Friends, family, or angels',      hint: 'Informal equity from individuals who know you.',          scores: { llc: 2, ccorp: 3 } },
      { id: 'venture',   label: 'Priced venture rounds',           hint: 'Institutional VC expecting preferred stock and options.', scores: { ccorp: 5 } },
      { id: 'donations', label: 'Grants & donations',              hint: 'Charitable giving, foundations, public support.',        scores: { nonprofit: 5 } },
    ],
  },
  {
    id: 'profit',
    eyebrow: 'Economics',
    title: 'What does profit look like in year two or three?',
    sub: 'A rough answer is fine — the goal is to see whether S-corp payroll math pencils out.',
    options: [
      { id: 'break',  label: 'Break-even or reinvesting', hint: 'Most revenue goes back into growth; little owner take-home.',  scores: { sole: 1, llc: 3, ccorp: 3 } },
      { id: 'modest', label: 'Under ~$60k net profit',    hint: 'Enough to pay yourself modestly; S-corp probably isn\'t worth it yet.', scores: { sole: 2, llc: 3 } },
      { id: 'solid',  label: '$60k–$250k net profit',     hint: 'The S-corp sweet spot for owner-operators.',                   scores: { scorp: 5, llc: 2 } },
      { id: 'big',    label: '$250k+ net profit',         hint: 'Serious self-employment tax; complex strategy territory.',      scores: { scorp: 3, ccorp: 3, llc: 2 } },
      { id: 'none',   label: 'Profit isn\'t the point',    hint: 'Surplus goes back to the mission, not shareholders.',          scores: { nonprofit: 5 } },
    ],
  },
  {
    id: 'payroll',
    eyebrow: 'Operations',
    title: 'Are you willing to run payroll for yourself?',
    sub: 'S-corps require owners to take a "reasonable" W-2 salary — real payroll, real filings, every pay period.',
    options: [
      { id: 'yes',   label: 'Yes — the tax savings are worth it', hint: 'You\'ll use a payroll provider and file quarterly returns.',     scores: { scorp: 4, ccorp: 2 } },
      { id: 'maybe', label: 'Maybe, once profit is high enough',  hint: 'Open to it, but only when the math clearly beats the cost.',   scores: { llc: 2, scorp: 2 } },
      { id: 'no',    label: 'No — keep it as simple as possible', hint: 'Prefer owner draws, one tax return, no payroll overhead.',      scores: { sole: 3, partnership: 2, llc: 3 } },
    ],
  },
  {
    id: 'horizon',
    eyebrow: 'Horizon',
    title: 'What\'s the plan for the business three to five years out?',
    sub: 'Exit path, ownership changes, and optionality all push you toward different structures.',
    options: [
      { id: 'lifestyle', label: 'A profitable lifestyle business', hint: 'Keep it small, keep it yours, take owner distributions.',          scores: { llc: 3, scorp: 3, sole: 2 } },
      { id: 'grow',      label: 'Grow, hire, maybe raise someday', hint: 'Scale the team; consider outside capital later.',                  scores: { llc: 3, ccorp: 2, scorp: 2 } },
      { id: 'venture',   label: 'Venture scale — exit or IPO',     hint: 'Raise priced rounds, issue options, sell or go public.',            scores: { ccorp: 5 } },
      { id: 'mission',   label: 'Sustain a mission indefinitely',   hint: 'Build a durable institution with no owners to pay out.',            scores: { nonprofit: 5 } },
    ],
  },
];

/* --- Icons ------------------------------------------------------------- */
function QIcon({ name, size = 14 }) {
  const common = { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'check':    return (<svg {...common}><path d="M3 8.5l3 3 7-7"/></svg>);
    case 'x':        return (<svg {...common}><path d="M4 4l8 8M12 4l-8 8"/></svg>);
    case 'dash':     return (<svg {...common}><path d="M4 8h8"/></svg>);
    case 'arrow':    return (<svg {...common}><path d="M3 8h10M9 4l4 4-4 4"/></svg>);
    case 'back':     return (<svg {...common}><path d="M13 8H3M7 4L3 8l4 4"/></svg>);
    case 'info':     return (<svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden><circle cx="8" cy="8" r="6.5" stroke="currentColor" strokeWidth="1.3"/><path d="M8 7v4M8 5.3v0" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>);
    case 'file':     return (<svg {...common}><path d="M4 2h6l3 3v9H4V2Z"/><path d="M10 2v3h3"/></svg>);
    case 'calendar': return (<svg {...common}><rect x="2.5" y="3.5" width="11" height="10" rx="1"/><path d="M2.5 6.5h11M6 2v3M10 2v3"/></svg>);
    case 'shield':   return (<svg {...common}><path d="M8 2l5 2v4c0 3-2.2 5.5-5 6-2.8-.5-5-3-5-6V4l5-2Z"/><path d="M6 8l1.5 1.5L11 6"/></svg>);
    case 'building': return (<svg {...common}><path d="M3 14V4h10v10"/><path d="M6 7h1M9 7h1M6 10h1M9 10h1"/></svg>);
    case 'split':    return (<svg {...common}><path d="M8 2v6M8 14v-3M3 8l5-2 5 2"/></svg>);
    default: return null;
  }
}

/* --- Helpers ----------------------------------------------------------- */
function computeScores(answers) {
  const totals = { sole: 0, partnership: 0, llc: 0, scorp: 0, ccorp: 0, nonprofit: 0 };
  QUESTIONS.forEach((q) => {
    const ans = answers[q.id];
    if (!ans) return;
    const opt = q.options.find(o => o.id === ans);
    if (!opt) return;
    Object.entries(opt.scores).forEach(([k, v]) => {
      totals[k] = (totals[k] || 0) + v;
    });
  });
  return totals;
}
function rankedEntities(scores) {
  return Object.entries(scores)
    .map(([k, v]) => ({ key: k, entity: ENTITIES[k], score: v }))
    .sort((a, b) => b.score - a.score);
}
function reasonsFor(entityKey, answers) {
  const reasons = [];
  QUESTIONS.forEach((q) => {
    const ans = answers[q.id];
    if (!ans) return;
    const opt = q.options.find(o => o.id === ans);
    if (!opt) return;
    const s = opt.scores[entityKey] || 0;
    if (s >= 3) {
      reasons.push({ q: q.eyebrow, choice: opt.label, hint: opt.hint });
    }
  });
  return reasons.slice(0, 4);
}

/* --- The quiz ---------------------------------------------------------- */
function EntityQuiz() {
  const [step, setStep] = useStateQuiz(0);               // 0..N-1 = question, N = result
  const [answers, setAnswers] = useStateQuiz({});
  const total = QUESTIONS.length;
  const isResult = step >= total;

  const scores = useMemoQuiz(() => computeScores(answers), [answers]);
  const ranked = useMemoQuiz(() => rankedEntities(scores), [scores]);
  const maxScore = Math.max(1, ...ranked.map(r => r.score));

  const q = QUESTIONS[step];
  const currentAnswer = q ? answers[q.id] : null;

  const canAdvance = !!currentAnswer;
  const isFinal = step === total - 1;

  const select = (optId) => {
    if (!q) return;
    setAnswers(a => ({ ...a, [q.id]: optId }));
  };
  const next = () => {
    if (!canAdvance) return;
    setStep(s => s + 1);
  };
  const back = () => setStep(s => Math.max(0, s - 1));
  const restart = () => { setAnswers({}); setStep(0); };

  const winner = ranked[0];
  const runners = ranked.slice(1, 3);

  return (
    <>
      <section className="container">
        <div className="quiz-hero">
          <div className="eyebrow">Resources · Tools</div>
          <h1 className="display">
            {isResult ? <>Your best-fit <em>structure.</em></> : <>Which <em>entity</em> should you form?</>}
          </h1>
          <p className="lede">
            {isResult
              ? 'Based on your answers, here\'s the structure that lines up best — plus the runners-up, the filings you\'ll owe, and the dates that actually matter.'
              : 'Six questions. No email required. We\'ll weigh liability, taxes, funding, and what you want three years out — then show you the structure that fits, with the filings and deadlines spelled out.'}
          </p>
        </div>
      </section>

      <section className="container" style={{ paddingBottom: 24 }}>
        <div className="quiz-shell">
          {!isResult && <QuestionPanel q={q} step={step} total={total} currentAnswer={currentAnswer} onSelect={select} onBack={back} onNext={next} canAdvance={canAdvance} isFinal={isFinal}/>}
          {!isResult && <PreviewPanel ranked={ranked} maxScore={maxScore} answered={Object.keys(answers).length} total={total}/>}
          {isResult && <ResultPanels winner={winner} runners={runners} answers={answers}/>}
        </div>

        {isResult && (
          <div className="quiz-restart-row">
            <a href="#" onClick={(e) => { e.preventDefault(); restart(); }}>↺ Start over</a>
          </div>
        )}

        {/* Disclaimer */}
        <div className="quiz-disclaimer">
          <div className="quiz-disclaimer-icon"><QIcon name="info" size={16}/></div>
          <div className="quiz-disclaimer-body">
            <strong>This is educational, not legal or tax advice.</strong> Entity selection depends on facts this quiz can't see — your state, industry, existing agreements, residency, spouse's situation, long-term plans, and a dozen other things. Rules, thresholds, and deadlines also change. Before you file, elect, or convert, talk to a qualified attorney and CPA about your specific circumstances. For help from someone who does this every day, <a href="cfo.html">talk to a Revenu advisor</a> or <a href="pricing.html">start a free trial</a>.
          </div>
        </div>
      </section>

      {/* Comparison table */}
      <section className="container quiz-compare-section">
        <div className="quiz-compare-head">
          <div>
            <div className="eyebrow">Reference</div>
            <h2>The six structures, <em>side by side.</em></h2>
          </div>
          <p className="lede">The same five questions, answered for every common entity type. Bookmark this — it's the sheet most founders wish they'd had the day they started.</p>
        </div>
        <ComparisonTable/>
      </section>
    </>
  );
}

/* --- Question Panel ---------------------------------------------------- */
function QuestionPanel({ q, step, total, currentAnswer, onSelect, onBack, onNext, canAdvance, isFinal }) {
  const pct = ((step) / total) * 100;
  return (
    <div className="quiz-question-panel">
      <div className="quiz-progress-head">
        <div className="quiz-progress-count"><strong>Question {step + 1}</strong> of {total}</div>
        <div className="quiz-progress-bar"><div className="quiz-progress-fill" style={{ width: `${pct + (100/total)*0.1}%` }}/></div>
      </div>

      <div className="quiz-question" key={q.id}>
        <div className="quiz-question-eyebrow">{q.eyebrow}</div>
        <h2>{q.title}</h2>
        <p className="quiz-question-sub">{q.sub}</p>

        <div className="quiz-options">
          {q.options.map((opt, i) => {
            const selected = currentAnswer === opt.id;
            const key = String.fromCharCode(65 + i); // A, B, C...
            return (
              <button
                key={opt.id}
                type="button"
                className={`quiz-option ${selected ? 'is-selected' : ''}`}
                onClick={() => onSelect(opt.id)}
              >
                <span className="quiz-option-key">{key}</span>
                <span>
                  <span className="quiz-option-label">{opt.label}</span>
                  <span className="quiz-option-hint">{opt.hint}</span>
                </span>
                <span className="quiz-option-check"><QIcon name="check" size={12}/></span>
              </button>
            );
          })}
        </div>
      </div>

      <div className="quiz-nav">
        <button className="quiz-back" onClick={onBack} disabled={step === 0}>
          <QIcon name="back" size={12}/> Back
        </button>
        <button className={`quiz-next ${isFinal ? 'is-final' : ''}`} onClick={onNext} disabled={!canAdvance}>
          {isFinal ? 'See my result' : 'Next question'} <QIcon name="arrow" size={12}/>
        </button>
      </div>
    </div>
  );
}

/* --- Preview (running scorecard) --------------------------------------- */
function PreviewPanel({ ranked, maxScore, answered, total }) {
  const hasAny = answered > 0;
  const leader = ranked[0];
  return (
    <div className="quiz-preview">
      <div className="quiz-preview-head">
        <div className="quiz-preview-title">Leaning toward</div>
        <span className="quiz-factor"><span className="dot"/> {answered}/{total} answered</span>
      </div>

      <div className="quiz-leader">
        <div className="quiz-leader-eyebrow">{hasAny ? 'Current leader' : 'Start the quiz'}</div>
        <div className="quiz-leader-name">
          {hasAny && leader.score > 0 ? <em>{leader.entity.nameEm}</em> : <em>—</em>}
        </div>
        <div className="quiz-leader-sub">
          {hasAny && leader.score > 0
            ? leader.entity.tagline
            : 'Answer a few questions and we\'ll start narrowing toward the structure that fits your business.'}
        </div>
      </div>

      <div className="quiz-scorecard">
        <div className="quiz-scorecard-head">
          <div className="quiz-scorecard-title">Fit scores</div>
          <div className="quiz-scorecard-meta">Live</div>
        </div>
        <div className="quiz-scorecard-list">
          {ranked.map((r, i) => {
            const pct = maxScore > 0 ? (r.score / maxScore) * 100 : 0;
            const cls = i === 0 && r.score > 0 ? 'is-top' : (r.score === 0 ? 'is-dim' : '');
            return (
              <div key={r.key} className={`quiz-score-row ${cls}`}>
                <div className="quiz-score-name">{r.entity.name}</div>
                <div className="quiz-score-bar-wrap">
                  <div className="quiz-score-bar" style={{ width: `${pct}%` }}/>
                </div>
                <div className="quiz-score-val">{r.score || 0}</div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="quiz-factors">
        <span className="quiz-factor"><span className="dot"/> Educational only</span>
        <span className="quiz-factor">No email required</span>
      </div>
    </div>
  );
}

/* --- Result view ------------------------------------------------------- */
function ResultPanels({ winner, runners, answers }) {
  const e = winner.entity;
  const reasons = reasonsFor(e.key, answers);
  return (
    <div className="quiz-result">
      <div className="quiz-result-main">
        <div className="quiz-result-eyebrow">Recommended structure</div>
        <h2 className="quiz-result-title"><em>{e.nameEm}</em></h2>
        <p className="quiz-result-tagline">{e.tagline}</p>

        <div className="quiz-result-reasons">
          <div className="quiz-question-eyebrow" style={{marginBottom: 4}}>Why this fits you</div>
          {reasons.length === 0 && (
            <div className="quiz-result-reason">
              <QIcon name="check" size={14}/>
              <span>{e.bestFor}</span>
            </div>
          )}
          {reasons.map((r, i) => (
            <div className="quiz-result-reason" key={i}>
              <QIcon name="check" size={14}/>
              <span><strong>{r.q}:</strong> {r.choice.toLowerCase()}. {r.hint}</span>
            </div>
          ))}
        </div>

        <div className="quiz-result-actions">
          <a href="cfo.html" className="btn btn-primary is-accent">Talk to a Revenu CFO <QIcon name="arrow" size={12}/></a>
          <a href="pricing.html" className="btn btn-secondary">See pricing</a>
        </div>
      </div>

      <div className="quiz-result-side">
        <div className="quiz-preview-title">Quick facts</div>
        <div className="quiz-facts">
          <FactRow icon="building" label="Incorporation required" fact={e.incorporation}/>
          <FactRow icon="shield"   label="Personal liability protection" fact={e.liability}/>
          <FactRow icon="split"    label="Pass-through taxation" fact={e.passthrough}/>
          <FactRow icon="file"     label="Federal tax form" fact={e.form}/>
          <FactRow icon="calendar" label="Filing deadline" fact={e.deadline}/>
        </div>

        <div className="quiz-runners">
          <div className="quiz-runners-title">Also worth considering</div>
          {runners.filter(r => r.score > 0).map((r, i) => (
            <div className="quiz-runner" key={r.key}>
              <div>
                <div className="quiz-runner-name">{r.entity.name}</div>
                <div className="quiz-runner-why">{r.entity.tagline}</div>
              </div>
              <div className="quiz-runner-score">{r.score} pts</div>
            </div>
          ))}
          {runners.every(r => r.score === 0) && (
            <div className="quiz-runner-why">No strong runners-up — your answers point clearly to one structure.</div>
          )}
        </div>
      </div>
    </div>
  );
}

function FactRow({ icon, label, fact }) {
  const cls =
    fact.kind === 'yes' ? 'is-yes' :
    fact.kind === 'no'  ? 'is-no'  : '';
  return (
    <div className="quiz-fact">
      <div className="quiz-fact-icon"><QIcon name={icon} size={14}/></div>
      <div>
        <div className="quiz-fact-label">{label}</div>
        <div className="quiz-runner-why" style={{marginTop: 2}}>{fact.note}</div>
      </div>
      <div className={`quiz-fact-value ${cls}`}>{fact.value}</div>
    </div>
  );
}

/* --- Comparison Table -------------------------------------------------- */
function ComparisonTable() {
  const order = ['sole', 'partnership', 'llc', 'scorp', 'ccorp', 'nonprofit'];
  const rows = [
    { key: 'incorporation', label: 'Incorporation required', sub: 'State filing to create the entity.' },
    { key: 'liability',     label: 'Liability protection',   sub: 'Does it shield personal assets?' },
    { key: 'passthrough',   label: 'Pass-through taxation',  sub: 'Income taxed at the owner level only.' },
    { key: 'form',          label: 'Federal tax form',       sub: 'What the IRS wants each year.' },
    { key: 'deadline',      label: 'Filing deadline',        sub: 'Calendar-year filers; extensions add six months.' },
  ];

  const cell = (entity, rowKey) => {
    const f = entity[rowKey];
    if (!f) return null;
    if (rowKey === 'form' || rowKey === 'deadline') {
      return (
        <td key={entity.key}>
          <span className="cell-mono cell-strong">{f.value}</span>
          <span className="cell-note">{f.note}</span>
        </td>
      );
    }
    // yes/no/partial cells
    let cls = 'cell-partial';
    let icon = 'dash';
    if (f.kind === 'yes') { cls = 'cell-yes'; icon = 'check'; }
    else if (f.kind === 'no') { cls = 'cell-no'; icon = 'x'; }
    return (
      <td key={entity.key}>
        <span className={cls}><QIcon name={icon} size={13}/> {f.value}</span>
        <span className="cell-note">{f.note}</span>
      </td>
    );
  };

  return (
    <div className="quiz-compare-wrap">
      <table className="quiz-compare">
        <thead>
          <tr>
            <th>Structure →</th>
            {order.map(k => (
              <th key={k}>
                {ENTITIES[k].nameEm}
                <span className="col-header-tag">{ENTITIES[k].name}</span>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map(row => (
            <tr key={row.key}>
              <td>
                {row.label}
                <span className="cell-note">{row.sub}</span>
              </td>
              {order.map(k => cell(ENTITIES[k], row.key))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { EntityQuiz });
