/* CoHaven — Holiday Co-Pilot (free tool)
   Divide the year's holidays, auto-alternate them year to year, keep it fair, print. */
const { useState, useEffect, useMemo } = React;
const { LeadGateModal, useLeadGate, PrintBrand, LeadNextStep } = window;

const COLORS = [
  { key:"teal",  c:"#1b4d4a", tint:"#d9e7e2", name:"Teal" },
  { key:"clay",  c:"#c96f4c", tint:"#f0d8c8", name:"Clay" },
  { key:"plum",  c:"#6d5080", tint:"#e4dcec", name:"Plum" },
  { key:"slate", c:"#3f6079", tint:"#d8e2ea", name:"Slate" },
  { key:"olive", c:"#6f7a3a", tint:"#e6e8d2", name:"Olive" },
  { key:"rose",  c:"#a8506a", tint:"#f0d6df", name:"Rose" },
];
const getColor = (key) => COLORS.find(c => c.key === key) || COLORS[0];

/* The year's holidays (label dates are typical; the tool is about who, not exact dates). */
const HOLIDAYS = [
  { id: "ny",    name: "New Year's Day",    when: "Jan 1" },
  { id: "mlk",   name: "MLK Day",           when: "3rd Mon Jan" },
  { id: "spring",name: "Spring break",      when: "Mar / Apr" },
  { id: "easter",name: "Easter weekend",    when: "Mar / Apr" },
  { id: "mem",   name: "Memorial Day",      when: "Last Mon May" },
  { id: "mom",   name: "Mother's Day",      when: "2nd Sun May" },
  { id: "dad",   name: "Father's Day",      when: "3rd Sun Jun" },
  { id: "jul4",  name: "Independence Day",  when: "Jul 4" },
  { id: "labor", name: "Labor Day",         when: "1st Mon Sep" },
  { id: "hall",  name: "Halloween",         when: "Oct 31" },
  { id: "thanks",name: "Thanksgiving",      when: "4th Thu Nov" },
  { id: "winter",name: "Winter break",      when: "Late Dec" },
];

/* Default alternating owner for a holiday in a given year.
   Mother's/Father's Day are sensible fixed defaults but still overridable. */
function defaultOwner(holIndex, holId, year) {
  if (holId === "mom") return "A";
  if (holId === "dad") return "B";
  return ((year + holIndex) % 2 === 0) ? "A" : "B";
}

function App() {
  const load = (k, def) => { try { const v = JSON.parse(localStorage.getItem("cohaven.holidays") || "{}")[k]; return v === undefined ? def : v; } catch (e) { return def; } };
  const thisYear = new Date().getFullYear();

  const [aName, setAName] = useState(() => load("aName", "You"));
  const [bName, setBName] = useState(() => load("bName", "Co-parent"));
  const [aColor, setAColor] = useState(() => load("aColor", "teal"));
  const [bColor, setBColor] = useState(() => load("bColor", "clay"));
  const [year, setYear] = useState(() => load("year", thisYear));
  // overrides: { [year]: { [holId]: 'A'|'B'|'split' } }
  const [overrides, setOverrides] = useState(() => load("overrides", {}));
  const [notes, setNotes] = useState(() => load("notes", { hall: "Trick-or-treat split — 4–7pm then swap", winter: "First half / second half — alternate the 25th" }));

  const { captured, open, gate, onCapture, dismiss } = useLeadGate();

  useEffect(() => {
    localStorage.setItem("cohaven.holidays", JSON.stringify({ aName, bName, aColor, bColor, year, overrides, notes }));
  }, [aName, bName, aColor, bColor, year, overrides, notes]);

  const colA = getColor(aColor), colB = getColor(bColor);
  const yearOv = overrides[year] || {};

  const ownerOf = (holIndex, holId) => yearOv[holId] || defaultOwner(holIndex, holId, year);

  const setOwner = (holId, val) => {
    setOverrides(o => ({ ...o, [year]: { ...(o[year] || {}), [holId]: val } }));
  };

  const resetYear = () => setOverrides(o => { const n = { ...o }; delete n[year]; return n; });

  const stats = useMemo(() => {
    let a = 0, b = 0, split = 0;
    HOLIDAYS.forEach((h, i) => {
      const w = ownerOf(i, h.id);
      if (w === "A") a++; else if (w === "B") b++; else split++;
    });
    const aShare = a + split / 2, bShare = b + split / 2;
    return { a, b, split, aShare, bShare, total: HOLIDAYS.length };
  }, [overrides, year]);

  const pct = (v) => stats.total ? (v / stats.total * 100) : 50;
  const diff = Math.abs(stats.aShare - stats.bShare);
  const fair = diff <= 1;

  const nameOf = (w) => w === "A" ? aName : w === "B" ? bName : "Split";
  const colOf = (w) => w === "A" ? colA.c : w === "B" ? colB.c : "#6d5080";

  return (
    <div className="sb">
      <header className="sb-nav no-print">
        <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>
        <span className="tool-tag">Free tool</span>
        <a className="btn btn-primary sb-cta" href="/pricing">Try the full app</a>
      </header>

      <div className="sb-head no-print">
        <span className="eyebrow">Holiday Co-Pilot</span>
        <h1>Divide the holidays once. Keep it fair for good.</h1>
        <p className="muted">Decide who has the kids for each holiday — or split it — and CoHaven alternates the assignments every year so it stays even. Saves automatically and prints clean. No account needed.</p>
      </div>

      <div className="sb-grid">
        <aside className="panel controls no-print">
          <div className="ctl">
            <label className="ctl-label">Parents</label>
            <div className="parent-row">
              <span className="pdot" style={{ background: colA.c }}></span>
              <input className="pin" value={aName} maxLength={18} onChange={e => setAName(e.target.value)} />
            </div>
            <ColorRow selected={aColor} exclude={bColor} onPick={setAColor} />
            <div className="parent-row" style={{ marginTop: 12 }}>
              <span className="pdot" style={{ background: colB.c }}></span>
              <input className="pin" value={bName} maxLength={18} onChange={e => setBName(e.target.value)} />
            </div>
            <ColorRow selected={bColor} exclude={aColor} onPick={setBColor} />
          </div>

          <div className="ctl">
            <label className="ctl-label">Year</label>
            <div className="year-nav">
              <button className="navb" onClick={() => setYear(y => y - 1)} aria-label="Previous year"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6" strokeLinecap="round" strokeLinejoin="round" /></svg></button>
              <span className="yr">{year}</span>
              <button className="navb" onClick={() => setYear(y => y + 1)} aria-label="Next year"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 18l6-6-6-6" strokeLinecap="round" strokeLinejoin="round" /></svg></button>
            </div>
            <p className="parity">Defaults <b>flip automatically</b> each year, so what's {aName}'s this year is {bName}'s the next.</p>
          </div>

          <div className="ctl">
            <label className="ctl-label">Quick actions</label>
            <button className="btn btn-ghost full altbtn" onClick={resetYear}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 12a9 9 0 1 0 3-6.7L3 8m0-5v5h5" strokeLinecap="round" strokeLinejoin="round" /></svg>
              Reset {year} to alternating
            </button>
            <p className="hint">Tip: set Halloween or winter break to <b>Split</b>, then add a note on how you'll divide the day.</p>
          </div>

          <div className="ctl">
            <button className="btn btn-ghost full" onClick={() => gate(() => window.print())}>
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2M6 14h12v8H6z" strokeLinecap="round" strokeLinejoin="round" /></svg>
              Print / save as PDF
            </button>
          </div>
        </aside>

        <main className="panel holwrap">
          <PrintBrand toolName="Holiday Co-Pilot" />
          <div className="hol-top">
            <h2>{year} holiday plan</h2>
            <span className="print-only" style={{ fontFamily: "var(--mono)", fontSize: 13, color: "var(--ink-500)" }}>{aName} &amp; {bName}</span>
          </div>

          <div className="tally">
            <div className="tally-bar">
              <span style={{ width: pct(stats.aShare) + "%", background: colA.c }}></span>
              <span style={{ width: pct(stats.split) + "%", background: "#6d5080", opacity: stats.split ? 1 : 0 }}></span>
              <span style={{ width: pct(stats.bShare - stats.split / 2) + "%", background: colB.c }}></span>
            </div>
            <div className="tally-nums">
              <span className="t"><i style={{ background: colA.c }}></i> {aName}: <b>{stats.a}</b></span>
              {stats.split > 0 && <span className="t"><i style={{ background: "#6d5080" }}></i> Split: <b>{stats.split}</b></span>}
              <span className="t"><i style={{ background: colB.c }}></i> {bName}: <b>{stats.b}</b></span>
              <span className={"balance-chip " + (fair ? "fair" : "off")}>{fair ? "Evenly split" : Math.round(diff) + " apart"}</span>
            </div>
          </div>

          <div className="hlist">
            {HOLIDAYS.map((h, i) => {
              const w = ownerOf(i, h.id);
              return (
                <div className={"hrow" + (w === "split" ? " split-on" : "")} key={h.id} style={{ borderLeft: "4px solid " + colOf(w) }}>
                  <div className="hl">
                    <div className="hn">{h.name} <span className="print-tag" style={{ background: colOf(w) + "22", color: colOf(w) }}>{nameOf(w)}</span></div>
                    <div className="hd">{h.when}</div>
                    {w === "split" && (
                      <input className="note-in no-print" placeholder="How will you split the day? (optional)" value={notes[h.id] || ""} maxLength={60} onChange={e => setNotes(n => ({ ...n, [h.id]: e.target.value }))} />
                    )}
                    {w === "split" && notes[h.id] && <div className="print-only hd" style={{ marginTop: 4 }}>↳ {notes[h.id]}</div>}
                  </div>
                  <div className="hseg no-print">
                    <button className={w === "A" ? "on" : ""} style={w === "A" ? { background: colA.c } : null} onClick={() => setOwner(h.id, "A")}>{aName}</button>
                    <button className={w === "split" ? "on" : ""} style={w === "split" ? { background: "#6d5080" } : null} onClick={() => setOwner(h.id, "split")}>Split</button>
                    <button className={w === "B" ? "on" : ""} style={w === "B" ? { background: colB.c } : null} onClick={() => setOwner(h.id, "B")}>{bName}</button>
                  </div>
                </div>
              );
            })}
          </div>
          <LeadNextStep
            captured={captured}
            title="Make the holiday plan easier to reuse."
            body="Your holiday plan is unlocked. CoHaven can keep the yearly plan, swaps, reminders, and handoff notes visible to both homes."
          />
        </main>
      </div>

      <footer className="sb-footer no-print">
        <p>Free from <b>CoHaven</b> — keep your schedule, expenses and reminders in one shared place. <a href="/pricing">Start a 30-day trial →</a></p>
      </footer>

      <LeadGateModal
        isOpen={open}
        onCapture={onCapture}
        onDismiss={dismiss}
        headline="Send your holiday plan to your email."
        subline="We'll email your holiday schedule as a PDF — and unlock printing on this device."
      />
    </div>
  );
}

function ColorRow({ selected, exclude, onPick }) {
  return (
    <div className="colorrow">
      {COLORS.map(col => (
        <button key={col.key} className={"sw" + (selected === col.key ? " on" : "")}
          disabled={col.key === exclude} style={{ background: col.c, opacity: col.key === exclude ? 0.25 : 1 }}
          title={col.name} onClick={() => onPick(col.key)} />
      ))}
    </div>
  );
}

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