/* CoHaven — Co-Parenting Check-In (free, private quiz)
   One question per screen · 5 calm dimensions · non-judgmental scored results.
   Nothing leaves the browser; answers persist locally so a refresh keeps your place. */
const { useState, useEffect } = React;
const { LeadGateModal, useLeadGate, PrintBrand, LeadNextStep } = window;

/* ---- dimensions ---- */
const DIMS = {
  comm:    { name: "Communication", color: "#1b4d4a" },
  logist:  { name: "Logistics & reliability", color: "#266b65" },
  consist: { name: "Consistency across homes", color: "#3f6079" },
  tone:    { name: "Conflict & tone", color: "#c96f4c" },
  kids:    { name: "Keeping kids out of the middle", color: "#6d5080" },
};

/* ---- questions ---- (reverse: higher frequency = worse) ---- */
const QUESTIONS = [
  { dim: "comm",    text: "We can exchange the practical details — pickups, appointments, school — without it turning into something bigger." },
  { dim: "tone",    text: "Messages between us stay calm and matter-of-fact, even when we disagree.", reverse: false },
  { dim: "logist",  text: "When one of us commits to a time or a handoff, it reliably happens." },
  { dim: "kids",    text: "Our kids get pulled in to carry messages or take sides between us.", reverse: true },
  { dim: "consist", text: "Bedtimes, screen time and the basic rules are roughly consistent in both homes." },
  { dim: "comm",    text: "I find out about important things (a doctor's visit, a school event) in good time, not at the last minute." },
  { dim: "tone",    text: "Old arguments resurface when we're only trying to sort out logistics.", reverse: true },
  { dim: "logist",  text: "Shared costs and reimbursements get settled without me having to chase them." },
  { dim: "kids",    text: "We present a united, predictable front to the kids on the things that matter." },
  { dim: "consist", text: "Plans we agree on tend to stick, rather than quietly changing between homes." },
];

/* Likert: index 0..3 -> raw 1..4 */
const OPTIONS = ["Rarely", "Sometimes", "Often", "Almost always"];

/* band thresholds (0-100) */
function band(score) {
  if (score >= 78) return { label: "Working well", color: "#2a7d54", tip: "well" };
  if (score >= 58) return { label: "Mostly steady", color: "#266b65", tip: "steady" };
  if (score >= 38) return { label: "Worth a look", color: "#c08a2e", tip: "look" };
  return { label: "Needs some care", color: "#a8512f", tip: "care" };
}

/* per-dimension guidance keyed by band tip */
const TIPS = {
  comm: {
    well: "Information flows early and cleanly. Keeping it in one shared place protects that as life gets busier.",
    steady: "Most details land in time. A shared calendar and a single thread for logistics close the occasional gap.",
    look: "Things are sometimes learned late. A neutral, shared record of dates and updates takes the memory out of it.",
    care: "Important details slip through. One source of truth — visible to both homes — removes the he-said/she-said.",
  },
  logist: {
    well: "Commitments hold and money settles itself. That reliability is the foundation everything else rests on.",
    steady: "Mostly dependable. Automatic reminders and a running expense balance remove the small frictions that linger.",
    look: "Follow-through wobbles. Logged handoffs and an itemised, shared balance make reliability visible, not personal.",
    care: "Plans and reimbursements need chasing. A timestamped shared log turns chasing into a glance.",
  },
  consist: {
    well: "The two homes feel like one plan to your kids. Writing the shared rules down keeps it that way through change.",
    steady: "Broadly aligned. A shared house-rules page settles the 'but at Dad's…' conversations before they start.",
    look: "Homes drift apart on the basics. Agreeing a short, written set of shared rules gives kids steadier ground.",
    care: "The rules differ enough to unsettle the kids. Start with three shared agreements, written where both can see them.",
  },
  tone: {
    well: "You keep heat out of the logistics. A structured, topic-by-topic format helps protect that on the hard days.",
    steady: "Tone is usually fine. Keeping messages tied to a specific item — not an open chat — stops spirals.",
    look: "Conversations can overheat. Structured, one-topic messages and a tone check keep things matter-of-fact.",
    care: "Logistics reopen old conflict. A neutral, item-by-item channel — no open-ended threads — lowers the temperature.",
  },
  kids: {
    well: "Your kids stay out of the middle. That's the thing that protects them most — keep guarding it.",
    steady: "Mostly shielded. Coordinating adult-to-adult, in one place, keeps it that way.",
    look: "Kids occasionally get drawn in. Moving message-passing to a direct, parent-only channel takes them out of it.",
    care: "Kids are carrying too much between you. A direct co-parent channel — never through them — is the first repair.",
  },
};

const OVERALL = {
  well: "Your co-parenting logistics are in a good place. CoHaven helps you keep them there as schedules and needs change.",
  steady: "You've got a workable rhythm with a few rough edges. Small structures around the friction points make a real difference.",
  look: "There are some real strain points here — and they're the ordinary, fixable kind. Giving the logistics a neutral, shared home is a calm place to start.",
  care: "The everyday coordination is taking a toll right now. None of this is a verdict on you — it's a sign the logistics need their own structure, separate from the relationship.",
};

function Ring({ pct, color }) {
  const r = 56, c = 2 * Math.PI * r;
  return (
    <div className="r-ring">
      <svg width="128" height="128" viewBox="0 0 128 128">
        <circle cx="64" cy="64" r={r} fill="none" stroke="var(--card-edge)" strokeWidth="11" />
        <circle cx="64" cy="64" r={r} fill="none" stroke={color} strokeWidth="11" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={c * (1 - pct / 100)} style={{ transition: "stroke-dashoffset .7s var(--ease)" }} />
      </svg>
      <div className="pct">{pct}<span style={{ fontSize: 18, color: "var(--ink-500)" }}>%</span></div>
    </div>
  );
}

function Brand() {
  return (
    <a className="brand" href="/">
      <svg className="logo-mark" viewBox="0 0 40 40" aria-hidden="true">
        <path className="a" d="M20 4 6 15v3l14-11 14 11v-3z" />
        <path className="b" d="M13 19c0-1 .8-2 2-2h10c1.2 0 2 1 2 2v13c0 1-.8 2-2 2H15c-1.2 0-2-1-2-2z" />
        <rect className="a" x="18" y="25" width="4" height="9" rx="1" />
      </svg>
      CoHaven
    </a>
  );
}

function App() {
  const saved = (() => { try { return JSON.parse(localStorage.getItem("cohaven.checkin") || "{}"); } catch (e) { return {}; } })();
  const [stage, setStage] = useState(saved.stage || "intro"); // intro | quiz | results
  const [idx, setIdx] = useState(saved.idx || 0);
  const [answers, setAnswers] = useState(saved.answers || {}); // qIndex -> 0..3

  useEffect(() => {
    localStorage.setItem("cohaven.checkin", JSON.stringify({ stage, idx, answers }));
  }, [stage, idx, answers]);

  const { captured, open, gate, onCapture, dismiss } = useLeadGate();
  useEffect(() => {
    if (stage === 'results') gate(null);
  }, [stage, gate]);

  const total = QUESTIONS.length;

  const choose = (val) => {
    const next = { ...answers, [idx]: val };
    setAnswers(next);
    setTimeout(() => {
      if (idx + 1 < total) setIdx(idx + 1);
      else setStage("results");
    }, 180);
  };

  const back = () => { if (idx > 0) setIdx(idx - 1); };
  const restart = () => { setAnswers({}); setIdx(0); setStage("intro"); };

  /* scoring */
  const score = () => {
    const acc = {}; const cnt = {};
    Object.keys(DIMS).forEach(k => { acc[k] = 0; cnt[k] = 0; });
    QUESTIONS.forEach((q, i) => {
      if (answers[i] === undefined) return;
      let raw = answers[i] + 1; // 1..4
      if (q.reverse) raw = 5 - raw; // invert
      const norm = (raw - 1) / 3 * 100; // 0..100
      acc[q.dim] += norm; cnt[q.dim]++;
    });
    const dims = {};
    Object.keys(DIMS).forEach(k => { dims[k] = cnt[k] ? Math.round(acc[k] / cnt[k]) : 0; });
    const overall = Math.round(Object.values(dims).reduce((a, b) => a + b, 0) / Object.keys(dims).length);
    return { dims, overall };
  };

  /* ---------------- INTRO ---------------- */
  if (stage === "intro") {
    return (
      <div>
        <header className="q-nav">
          <Brand />
          <span className="tool-tag">Free check-in</span>
          <a className="btn btn-primary sb-cta" href="/pricing">Try the full app</a>
        </header>
        <div className="q-wrap">
          <div className="q-intro">
            <span className="eyebrow">Co-Parenting Check-In</span>
            <h1>How is the co-parenting actually going?</h1>
            <p>Ten short questions about the everyday logistics between your two homes. No right answers, no judgement — just an honest, private picture of what's working and what strains.</p>
            <div className="q-meta">
              <span className="m"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" strokeLinecap="round" strokeLinejoin="round" /></svg> About 2 minutes</span>
              <span className="m"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="4" y="10" width="16" height="11" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" strokeLinecap="round" /></svg> Completely private</span>
              <span className="m"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 11l3 3 8-8M3 12l3 3" strokeLinecap="round" strokeLinejoin="round" /></svg> No sign-up</span>
            </div>
            <div className="q-start">
              <button className="btn btn-accent btn-lg" onClick={() => { setStage("quiz"); setIdx(0); }}>
                {Object.keys(answers).length > 0 && idx > 0 ? "Resume check-in" : "Start the check-in"}
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </button>
            </div>
            <p className="q-priv">Your answers stay in this browser. Nothing is uploaded or shared.</p>
          </div>
        </div>
      </div>
    );
  }

  /* ---------------- QUIZ ---------------- */
  if (stage === "quiz") {
    const q = QUESTIONS[idx];
    const dim = DIMS[q.dim];
    const cur = answers[idx];
    return (
      <div>
        <header className="q-nav">
          <Brand />
          <span className="tool-tag">Free check-in</span>
        </header>
        <div className="q-wrap">
          <div className="q-prog">
            <div className="bar"><span style={{ width: ((idx) / total * 100) + "%" }}></span></div>
            <span className="count">{idx + 1} / {total}</span>
          </div>
          <div className="q-card" key={idx}>
            <div className="q-dim" style={{ color: dim.color }}>{dim.name}</div>
            <div className="q-text">{q.text}</div>
            <div className="q-opts">
              {OPTIONS.map((o, i) => (
                <button key={i} className={"q-opt" + (cur === i ? " on" : "")} onClick={() => choose(i)}>
                  <span className="rad"></span>{o}
                </button>
              ))}
            </div>
            <div className="q-foot">
              <button className="q-back" onClick={back} disabled={idx === 0}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M15 18l-6-6 6-6" strokeLinecap="round" strokeLinejoin="round" /></svg>
                Back
              </button>
              <span className="q-skip">Answer honestly — it's just for you</span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ---------------- RESULTS ---------------- */
  const { dims, overall } = score();
  const ob = band(overall);
  return (
    <div>
      <LeadGateModal
        isOpen={open}
        onCapture={onCapture}
        onDismiss={dismiss}
        headline="Your check-in results are ready."
        subline="Enter your email to see your personalised breakdown — we'll send you a copy to keep."
      />
      <header className="q-nav">
        <Brand />
        <span className="tool-tag">Your check-in</span>
        <a className="btn btn-primary sb-cta" href="/pricing">Try the full app</a>
      </header>
      <div className="q-wrap">
        <PrintBrand toolName="Co-Parenting Check-In" />
        <div className="r-head">
          <span className="eyebrow">Your check-in</span>
          <h1>Where things stand today.</h1>
        </div>

        <div className="r-overall">
          <Ring pct={overall} color={ob.color} />
          <div className="band" style={{ color: ob.color }}>{ob.label}</div>
          <p className="blurb">{OVERALL[ob.tip]}</p>
        </div>

        <div className="r-dims">
          {Object.keys(DIMS).map(k => {
            const v = dims[k]; const b = band(v);
            return (
              <div className="r-dim" key={k}>
                <div className="r-dim-top">
                  <span className="dn">{DIMS[k].name}</span>
                  <span className="dl" style={{ color: b.color }}>{b.label}</span>
                </div>
                <div className="dbar"><span style={{ width: v + "%", background: b.color }}></span></div>
                <p className="dtip">{TIPS[k][b.tip]}</p>
              </div>
            );
          })}
        </div>

        <div className="r-cta">
          <h2>Give the logistics a calmer home.</h2>
          <p>CoHaven puts your schedule, expenses, handoffs and reminders in one shared, neutral place — so the everyday details stop becoming the friction.</p>
          <div className="acts">
            <a className="btn btn-accent btn-lg" href="/pricing">Start a 30-day trial</a>
            <a className="btn btn-ghost btn-lg" href="/">See how it works</a>
          </div>
        </div>
        <LeadNextStep
          captured={captured}
          title="Turn the insight into a calmer workflow."
          body="Your result is unlocked. CoHaven gives daily logistics a calmer structure: shared schedule, expenses, reminders, and records."
        />

        <div className="r-foot">
          <button className="r-restart" onClick={restart}>Retake the check-in</button>
        </div>
        <p className="r-disc">This check-in is a private reflection tool, not a clinical, diagnostic, or legal assessment. If you're worried about safety, contact a local professional or support line.</p>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
