// Polished SmartAsset homepage with all new sections.
// Reuses .sa namespace from v3-styles.css + adds homepage-sa.css.

const { useState: useHpState, useMemo: useHpMemo } = React;

// ---------- Live mini-estimator for hero card ----------
function HeroCalc() {
  const [step, setStep] = useHpState(0);
  const [answers, setAnswers] = useHpState({ prop: null, w2: null, mp: null });
  const result = useHpMemo(
    () => (answers.prop && answers.w2 && answers.mp === "yes") ? computeEstimate(answers.prop, answers.w2) : null,
    [answers]
  );

  const propKeys = Object.keys(PROPERTY_BUCKETS);
  const w2Keys = Object.keys(W2_BUCKETS);
  const cta = "Order my study";

  function pick(key, value) {
    setAnswers(a => ({ ...a, [key]: value }));
    setTimeout(() => setStep(s => Math.min(s + 1, 3)), 160);
  }
  function reset() { setStep(0); setAnswers({ prop: null, w2: null, mp: null }); }

  // Disqualified path
  const disq = answers.mp === "no";

  const stepDot = (i) => {
    let cls = "step-dot";
    if (step > i) cls += " is-done";
    else if (step === i) cls += " is-active";
    return cls;
  };
  const stepLine = (i) => "step-line" + (step > i ? " is-done" : "");

  return (
    <aside className="sa-calc-card">
      <div className="sa-calc-head">
        <div>
          <div className="lbl">W-2 Offset Calculator</div>
          <div className="ttl">Estimate your savings · 30 sec</div>
        </div>
        <span className="badge">Live</span>
      </div>
      <div className="sa-calc-body">
        {step < 3 && (
          <div className="sa-calc-progress">
            <span className={stepDot(0)}>{step > 0 ? "✓" : "1"}</span>
            <span className={stepLine(0)}></span>
            <span className={stepDot(1)}>{step > 1 ? "✓" : "2"}</span>
            <span className={stepLine(1)}></span>
            <span className={stepDot(2)}>{step > 2 ? "✓" : "3"}</span>
          </div>
        )}

        {step === 0 && (
          <>
            <div className="sa-calc-q">What did you (or will you) pay for the property?</div>
            <div className="sa-calc-help">Excluding land — we'll model 30% reclassified to 5/15-year property.</div>
            <div className="sa-calc-options">
              {propKeys.map(k => (
                <button key={k} className={`sa-calc-pill ${answers.prop === k ? "is-active" : ""}`} onClick={() => pick("prop", k)}>
                  <span>{PROPERTY_BUCKETS[k].label}</span><span className="arrow">→</span>
                </button>
              ))}
            </div>
          </>
        )}

        {step === 1 && (
          <>
            <div className="sa-calc-q">Your W-2 income (you + spouse if joint)?</div>
            <div className="sa-calc-help">Determines your federal marginal bracket.</div>
            <div className="sa-calc-options">
              {w2Keys.map(k => (
                <button key={k} className={`sa-calc-pill ${answers.w2 === k ? "is-active" : ""}`} onClick={() => pick("w2", k)}>
                  <span>{W2_BUCKETS[k].label}</span><span className="arrow">→</span>
                </button>
              ))}
            </div>
          </>
        )}

        {step === 2 && (
          <>
            <div className="sa-calc-q">Will you spend 100+ hours managing the STR — and more than anyone else?</div>
            <div className="sa-calc-help">Material participation under §469 — required for losses to offset W-2.</div>
            <div className="sa-calc-options">
              <button className={`sa-calc-pill ${answers.mp === "yes" ? "is-active" : ""}`} onClick={() => pick("mp", "yes")}>
                <span>Yes — I'll be the primary operator</span><span className="arrow">→</span>
              </button>
              <button className={`sa-calc-pill ${answers.mp === "no" ? "is-active" : ""}`} onClick={() => pick("mp", "no")}>
                <span>No / using a property manager</span><span className="arrow">→</span>
              </button>
            </div>
          </>
        )}

        {step === 3 && !disq && result && (
          <div className="sa-calc-result">
            <div className="sa-calc-result-lbl">Estimated Year-1 W-2 Tax Reduction</div>
            <div className="sa-calc-result-num">{fmt$(result.reduction)}</div>
            <div className="sa-calc-result-sub">For a {PROPERTY_BUCKETS[answers.prop].label.toLowerCase()} property at the {Math.round(W2_BUCKETS[answers.w2].bracket * 100)}% bracket.</div>
            <div className="sa-calc-breakdown">
              <div className="sa-calc-breakdown-row"><span className="k">Property basis (mid)</span><span className="v">{fmt$(PROPERTY_BUCKETS[answers.prop].mid)}</span></div>
              <div className="sa-calc-breakdown-row"><span className="k">Reclassified to 5/15-yr (30%)</span><span className="v">{fmt$(result.deduction)}</span></div>
              <div className="sa-calc-breakdown-row"><span className="k">× Federal bracket</span><span className="v">{Math.round(W2_BUCKETS[answers.w2].bracket * 100)}%</span></div>
              <div className="sa-calc-breakdown-row"><span className="k">Study fee</span><span className="v">−{fmt$(result.fee)}</span></div>
              <div className="sa-calc-breakdown-row total"><span className="k">Net Year-1 benefit</span><span className="v">{fmt$(result.reduction - result.fee)}</span></div>
            </div>
            <div className="sa-calc-actions">
              <a href={ORDER_URL} className="sa-calc-cta">{cta} →</a>
              <button className="sa-calc-reset" onClick={reset}>Restart</button>
            </div>
          </div>
        )}

        {step === 3 && disq && (
          <div className="sa-calc-result">
            <div className="sa-calc-result-lbl">Heads up</div>
            <div className="sa-calc-result-num" style={{ fontSize: 32, marginTop: 12 }}>Material participation needed</div>
            <div className="sa-calc-result-sub">Without 100+ hours and being the primary operator, STR losses stay passive and can't offset W-2. You'd need REPS instead — let's chat.</div>
            <div className="sa-calc-actions">
              <a href={ORDER_URL} className="sa-calc-cta">Talk to us anyway →</a>
              <button className="sa-calc-reset" onClick={reset}>Restart</button>
            </div>
          </div>
        )}
      </div>
      <div className="sa-calc-foot">
        <span className="lock">🔒 No email · No signup</span>
        <span>30% reclass · 100% bonus depreciation</span>
      </div>
    </aside>
  );
}

// ---------- FAQ accordion ----------
function FAQ() {
  const [open, setOpen] = useHpState(0);
  const items = [
    {
      q: "Will my CPA actually accept this report?",
      a: "Yes. Our reports follow the IRS Audit Technique Guide for Cost Segregation (Pub. 5653) and use RSMeans 2024 cost data. We've delivered 4,000+ studies, and CPAs at every Big Four firm have filed returns with our work. If your CPA can't use it, we revise it free or refund the study — that's the <em>CPA-Ready Guarantee</em>."
    },
    {
      q: "Does cost segregation increase my audit risk?",
      a: "No measurable increase. The IRS itself wrote the Audit Technique Guide we follow. STR/W-2 offset is a well-established strategy — the law (§469, Reg. §1.469-1T) is over 30 years old. What triggers audits is sloppy substantiation, which is exactly what an engineering-based study prevents. Every report includes the workpapers your CPA hands the IRS if questions come up."
    },
    {
      q: "Do I need Real Estate Professional Status (REPS)?",
      a: "<em>No</em> — that's the whole point of the STR loophole. REPS requires 750+ hours and more time in real estate than any other job, which most W-2 earners can't claim. The 7-day average rule under §469 reclassifies STRs as a non-rental trade or business, so you only need to materially participate (100+ hours) — not qualify as a real estate professional."
    },
    {
      q: "What's included for $495?",
      a: "A full engineering-based cost segregation report: site analysis, asset reclassification, depreciation schedules for 5/15/27.5/39-yr property, IRS Form 3115 if needed, and all workpapers. Properties under $300K basis qualify for the $495 tier. Larger properties scale up — see our <em>Pricing</em> section. Same engineering team across all tiers."
    },
    {
      q: "How fast is turnaround?",
      a: "Most studies are delivered in <em>under an hour</em> after you complete the property questionnaire. Complex properties (rehabs, mixed-use, multi-unit) can take 1–2 business days. We don't charge a rush fee — same-day is standard."
    },
    {
      q: "Can I do this for a property I already own?",
      a: "<em>Yes</em>, and it's often the most powerful play. A look-back study lets you catch up missed depreciation in a single year via Form 3115 — no need to amend prior returns. We can study any property placed in service back to 1987. Many clients do this in Year 2 or 3 of ownership and recover six figures in deferred deductions."
    },
  ];
  return (
    <div className="sa-faq-list">
      {items.map((it, i) => (
        <div key={i} className={`sa-faq-item ${open === i ? "is-open" : ""}`}>
          <button className="sa-faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
            <span>{it.q}</span><span className="chev">+</span>
          </button>
          <div className="sa-faq-a"><div className="sa-faq-a-inner" dangerouslySetInnerHTML={{ __html: it.a }} /></div>
        </div>
      ))}
    </div>
  );
}

window.HeroCalc = HeroCalc;
window.FAQ = FAQ;
