// Shared atoms used across all 4 directions.
// Exported to window so other Babel scripts can import them.

const { useState, useMemo, useEffect } = React;

const fmt$ = (n) => "$" + Math.round(n).toLocaleString("en-US");
const fmt$k = (n) => "$" + Math.round(n / 1000).toLocaleString("en-US") + "K";

// ----- Estimator math (shared) ------------------------------------------------
// Rough midpoints for the buckets, multiplied by reclassified % at chosen
// bracket. The brief uses a $750K · 30% · 37% example yielding $52,688 — the
// math here matches that flow.
const PROPERTY_BUCKETS = {
  under300:  { label: "Under $300K",   mid: 240000 },
  mid:       { label: "$300K – $700K", mid: 500000 },
  high:      { label: "$700K – $1.5M", mid: 950000 },
  over15:    { label: "$1.5M+",        mid: 1800000 },
};
const W2_BUCKETS = {
  low:  { label: "$100K – $200K", bracket: 0.24 },
  mid:  { label: "$200K – $400K", bracket: 0.32 },
  high: { label: "$400K+",        bracket: 0.37 },
};
const RECLASS = 0.30; // 30% of basis reclassified to 5/15-yr (mid-case)

function studyFee(propertyMid) {
  if (propertyMid < 300000) return 495;
  if (propertyMid < 700000) return 895;
  if (propertyMid < 1500000) return 1495;
  return 2995;
}

function computeEstimate(propKey, w2Key) {
  const p = PROPERTY_BUCKETS[propKey];
  const w = W2_BUCKETS[w2Key];
  if (!p || !w) return null;
  const deduction = Math.round(p.mid * RECLASS);
  const reduction = Math.round(deduction * w.bracket);
  const fee = studyFee(p.mid);
  return {
    deduction, reduction, fee,
    bracket: w.bracket,
    propertyMid: p.mid,
    propertyLabel: p.label,
    w2Label: w.label,
    roi: Math.round(reduction / fee),
  };
}

// ----- CTA URL ----------------------------------------------------------------
const ORDER_URL = "https://costsegsmart.com/order/?ref=w2&utm_source=costsegw2&utm_medium=site&utm_campaign=w2_offset";

// ----- Wordmark ---------------------------------------------------------------
function Wordmark({ tagline = true }) {
  return (
    <div className="nav-brand">
      <span className="nav-brand-mark">
        costseg<span style={{ color: "var(--gold-deep)" }}>w2</span>
      </span>
      {tagline && (
        <span className="nav-brand-tag">A Cost Seg Smart vertical</span>
      )}
    </div>
  );
}

function NavBar({ ctaCopy = "Order my study" }) {
  return (
    <header className="nav">
      <Wordmark />
      <nav className="nav-links">
        <a href="#how">How it works</a>
        <a href="#example">Example</a>
        <a href="#qualify">Qualify</a>
        <a href="#faq">FAQ</a>
        <a href={ORDER_URL} className="btn btn-primary" style={{ height: 38, padding: "0 16px", fontSize: 13 }}>
          {ctaCopy}
        </a>
      </nav>
    </header>
  );
}

// ----- Trust masthead ---------------------------------------------------------
function TrustMasthead() {
  const items = [
    "CPA-Ready Guarantee",
    "IRS ATG Pub. 5653 compliant",
    "RSMeans 2024 data",
    "Delivered in under 1 hour",
    "All 50 states",
  ];
  return (
    <div className="masthead">
      {items.map((t, i) => (
        <React.Fragment key={t}>
          <span>{t}</span>
          {i < items.length - 1 && <span className="dot" />}
        </React.Fragment>
      ))}
    </div>
  );
}

// ----- Estimator (3-step quiz) ------------------------------------------------
function Estimator({ variant = "default", onResult }) {
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({ prop: null, w2: null, mp: null });
  const result = useMemo(() => {
    if (answers.prop && answers.w2) return computeEstimate(answers.prop, answers.w2);
    return null;
  }, [answers]);

  useEffect(() => { if (onResult) onResult(result); }, [result]);

  const propKeys = Object.keys(PROPERTY_BUCKETS);
  const w2Keys = Object.keys(W2_BUCKETS);

  function pick(key, value) {
    setAnswers(a => ({ ...a, [key]: value }));
    setTimeout(() => setStep(s => Math.min(s + 1, 3)), 180);
  }

  function reset() {
    setStep(0);
    setAnswers({ prop: null, w2: null, mp: null });
  }

  const stepCopy = [
    { eyebrow: "Question 01 / 03", q: "What did you (or will you) pay for the property?" },
    { eyebrow: "Question 02 / 03", q: "What's your W-2 income (you + spouse if joint)?" },
    { eyebrow: "Question 03 / 03", q: "Will you spend 100+ hours managing the STR this year — and more than anyone else?" },
  ];

  return (
    <div className={`estimator estimator--${variant}`}>
      <div className="estimator-head">
        <div className="quiz-progress">
          {[0,1,2].map(i => <span key={i} className={`quiz-dot ${i <= step ? "is-on" : ""}`} />)}
        </div>
        {step < 3 && (
          <span className="eyebrow" style={{ marginLeft: 14 }}>{stepCopy[step].eyebrow}</span>
        )}
        {step === 3 && (
          <button className="btn-ghost" onClick={reset} style={{ background: "transparent", border: 0, fontSize: 12, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--fg-muted)", padding: 0 }}>
            ← Re-estimate
          </button>
        )}
      </div>

      {step === 0 && (
        <>
          <h3 className="estimator-q">{stepCopy[0].q}</h3>
          <div className="quiz-step-buttons">
            {propKeys.map(k => (
              <button key={k} className={`quiz-pill ${answers.prop === k ? "is-active" : ""}`} onClick={() => pick("prop", k)}>
                {PROPERTY_BUCKETS[k].label}
              </button>
            ))}
          </div>
        </>
      )}

      {step === 1 && (
        <>
          <h3 className="estimator-q">{stepCopy[1].q}</h3>
          <div className="quiz-step-buttons">
            {w2Keys.map(k => (
              <button key={k} className={`quiz-pill ${answers.w2 === k ? "is-active" : ""}`} onClick={() => pick("w2", k)}>
                {W2_BUCKETS[k].label}
              </button>
            ))}
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <h3 className="estimator-q">{stepCopy[2].q}</h3>
          <div className="quiz-step-buttons">
            {[
              { k: "yes", l: "Yes" },
              { k: "maybe", l: "Not sure" },
              { k: "no", l: "No" },
            ].map(o => (
              <button key={o.k} className={`quiz-pill ${answers.mp === o.k ? "is-active" : ""}`} onClick={() => pick("mp", o.k)}>
                {o.l}
              </button>
            ))}
          </div>
        </>
      )}

      {step === 3 && result && (
        <EstimatorResult result={result} mp={answers.mp} reset={reset} />
      )}
    </div>
  );
}

function EstimatorResult({ result, mp, reset }) {
  // Branch on material participation answer
  if (mp === "no") {
    return (
      <div className="estimator-result estimator-result--warn">
        <span className="eyebrow" style={{ color: "var(--gold-deep)" }}>Different path</span>
        <h3 style={{ fontSize: 28, marginTop: 8 }}>You probably need REPS — not the STR loophole.</h3>
        <p style={{ color: "var(--fg-muted)", marginTop: 10, maxWidth: 460 }}>
          Without 100+ hours of material participation, an STR's losses stay passive. Read the 7-Day Rule explainer for the alternate route.
        </p>
        <div style={{ marginTop: 22, display: "flex", gap: 10, flexWrap: "wrap" }}>
          <a href="#7day" className="btn btn-secondary">Read the 7-Day Rule</a>
          <button className="btn btn-ghost" onClick={reset}>Re-estimate</button>
        </div>
      </div>
    );
  }
  if (mp === "maybe") {
    return (
      <div className="estimator-result estimator-result--maybe">
        <span className="eyebrow" style={{ color: "var(--gold-deep)" }}>One step left</span>
        <h3 style={{ fontSize: 28, marginTop: 8 }}>Take the Material Participation Test.</h3>
        <p style={{ color: "var(--fg-muted)", marginTop: 10, maxWidth: 480 }}>
          Six questions. Two minutes. Confirms whether your hours qualify before you spend a dollar on the study.
        </p>
        <div style={{ marginTop: 22, display: "flex", gap: 10, flexWrap: "wrap" }}>
          <a href="#qualify" className="btn btn-primary">Take the test →</a>
          <button className="btn btn-ghost" onClick={reset}>Re-estimate</button>
        </div>
      </div>
    );
  }
  // qualifying
  return (
    <div className="estimator-result estimator-result--win">
      <span className="eyebrow" style={{ color: "rgba(255,255,255,0.7)" }}>Estimated Year-1 W-2 tax reduction</span>
      <div className="estimator-bignum num">{fmt$(result.reduction)}</div>
      <div className="estimator-result-meta num">
        On <strong>{fmt$(result.deduction)}</strong> of accelerated deductions
        <span className="estimator-sep" />
        Study fee <strong>{fmt$(result.fee)}</strong>
        <span className="estimator-sep" />
        <strong>{result.roi}×</strong> return
      </div>
      <div className="estimator-cta-row">
        <a href={ORDER_URL} className="btn btn-primary btn-arrow" style={{ background: "var(--gold)", color: "var(--fg)", borderColor: "var(--gold)" }}>
          {window.__W2_CTA_PRIMARY || "Order my study"}
        </a>
        <a href="#playbook" className="btn btn-ghost" style={{ color: "#fff" }}>
          Download the playbook →
        </a>
      </div>
      <div className="estimator-fineprint">
        Estimate based on 30% reclassification at {Math.round(result.bracket * 100)}% federal bracket. Your CPA verifies the actual figure.
      </div>
    </div>
  );
}

// Expose
Object.assign(window, {
  fmt$, fmt$k,
  PROPERTY_BUCKETS, W2_BUCKETS, computeEstimate,
  ORDER_URL,
  Wordmark, NavBar, TrustMasthead,
  Estimator, EstimatorResult,
});
