/* CoHaven — Shift Parent OS (free tool)
   Map a shift rotation onto the calendar, mark the days you have the kids,
   and surface exactly where work + custody collide (you need coverage). */
const { useState, useEffect, useMemo, useCallback } = React;
const { LeadGateModal, useLeadGate, PrintBrand, LeadNextStep } = window;

/* ---- shift presets: cycle length + which cycle-days are WORK days ---- */
const PRESETS = {
  "4-4":   { label: "4 on / 4 off", blurb: "Four days working, four days off — rolling.", len: 8, on: [true,true,true,true,false,false,false,false] },
  "3-3":   { label: "3 on / 3 off", blurb: "Three on, three off — a fast six-day cycle.", len: 6, on: [true,true,true,false,false,false] },
  "5-2":   { label: "5 on / 2 off", blurb: "A standard working week with the weekend off.", len: 7, on: [true,true,true,true,true,false,false] },
  "7-7":   { label: "7 on / 7 off", blurb: "A full week of shifts, then a full week off.", len: 14, on: [true,true,true,true,true,true,true,false,false,false,false,false,false,false] },
  "2-2-3": { label: "2-2-3 (Panama)", blurb: "Common rotating-shift pattern over two weeks.", len: 14, on: [true,true,false,false,true,true,true,false,false,true,true,false,false,true] },
  "custom":{ label: "Custom", blurb: "Toggle your own on/off pattern below.", len: 8, on: [true,true,true,true,false,false,false,false] },
};

function ymd(d){ return d.getFullYear()+"-"+String(d.getMonth()+1).padStart(2,"0")+"-"+String(d.getDate()).padStart(2,"0"); }
function parseYmd(s){ const [y,m,d]=s.split("-").map(Number); return new Date(y, m-1, d); }
function diffDays(a, b){ const s=new Date(a.getFullYear(),a.getMonth(),a.getDate()); const d=new Date(b.getFullYear(),b.getMonth(),b.getDate()); return Math.round((d-s)/86400000); }
function mod(n,m){ return ((n % m) + m) % m; }

const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const DOW = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];

const C = {
  work:    { bg: "#f3e3dc", fg: "#a8512f", label: "Working" },
  withyou: { bg: "#d9e7e2", fg: "#1b4d4a", label: "With you" },
  cover:   { bg: "#FEF5E4", fg: "#b3760a", border: "#d8a43e", label: "Needs cover" },
  off:     { bg: "#f1ece1", fg: "#8e978f", label: "Off" },
};

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

  const [name, setName] = useState(()=>load("name","You"));
  const [preset, setPreset] = useState(()=>load("preset","4-4"));
  const [customOn, setCustomOn] = useState(()=>load("customOn", PRESETS["custom"].on.slice()));
  const [customLen, setCustomLen] = useState(()=>load("customLen", 8));
  const [anchor, setAnchor] = useState(()=>load("anchor", todayStr));
  const [kidDays, setKidDays] = useState(()=>load("kidDays", {})); // ymd -> true
  const [view, setView] = useState(()=>{ const d=new Date(); return { y:d.getFullYear(), m:d.getMonth() }; });

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

  useEffect(()=>{
    localStorage.setItem("cohaven.shift", JSON.stringify({ name, preset, customOn, customLen, anchor, kidDays }));
  },[name, preset, customOn, customLen, anchor, kidDays]);

  const pattern = useMemo(()=>{
    if (preset === "custom") return { len: customLen, on: customOn.slice(0, customLen) };
    return PRESETS[preset];
  },[preset, customOn, customLen]);

  const start = parseYmd(anchor);
  const isWork = useCallback((date)=>{
    const i = mod(diffDays(start, date), pattern.len);
    return !!pattern.on[i];
  },[pattern, anchor]);

  const grid = useMemo(()=>{
    const first = new Date(view.y, view.m, 1);
    const pad = first.getDay();
    const dim = new Date(view.y, view.m+1, 0).getDate();
    const cells = [];
    for (let i=0;i<pad;i++) cells.push(null);
    for (let d=1; d<=dim; d++) cells.push(new Date(view.y, view.m, d));
    while (cells.length % 7 !== 0) cells.push(null);
    return cells;
  },[view]);

  const stateOf = (date)=>{
    const work = isWork(date);
    const kids = !!kidDays[ymd(date)];
    if (work && kids) return "cover";
    if (!work && kids) return "withyou";
    if (work) return "work";
    return "off";
  };

  const monthStats = useMemo(()=>{
    let work=0, off=0, kids=0, cover=0;
    const dim = new Date(view.y, view.m+1, 0).getDate();
    const coverList = [];
    for(let d=1; d<=dim; d++){
      const date = new Date(view.y, view.m, d);
      const w = isWork(date), k = !!kidDays[ymd(date)];
      if (w) work++; else off++;
      if (k) kids++;
      if (w && k) coverList.push(date);
    }
    return { work, off, kids, cover: coverList.length, coverList };
  },[view, pattern, anchor, kidDays]);

  const toggleKid = (date)=>{
    const key = ymd(date);
    setKidDays(o=>{ const n={...o}; if(n[key]) delete n[key]; else n[key]=true; return n; });
  };
  const toggleCustom = (i)=> setCustomOn(o=>{ const n=o.slice(); n[i]=!n[i]; return n; });
  const nav = (delta)=> setView(v=>{ let m=v.m+delta, y=v.y; if(m<0){m=11;y--;} if(m>11){m=0;y++;} return {y,m}; });
  const goToday = ()=>{ const d=new Date(); setView({y:d.getFullYear(), m:d.getMonth()}); };
  const clearKids = ()=> setKidDays({});
  const todayKey = ymd(new Date());

  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">Shift Parent OS</span>
        <h1>Make irregular shifts work with custody.</h1>
        <p className="muted">Set your rotation, mark the days you're scheduled to have the kids, and CoHaven instantly flags where a shift and a custody day collide — so you can line up a swap or coverage early. Saves automatically; prints clean.</p>
      </div>

      <div className="sb-grid">
        <aside className="panel controls no-print">
          <div className="ctl">
            <label className="ctl-label">Your name</label>
            <div className="parent-row">
              <span className="pdot" style={{background:"#a8512f"}}></span>
              <input className="pin" value={name} maxLength={18} onChange={e=>setName(e.target.value)} />
            </div>
          </div>

          <div className="ctl">
            <label className="ctl-label">Shift rotation</label>
            <div className="preset-list">
              {Object.entries(PRESETS).map(([k,p])=>(
                <button key={k} className={"preset"+(preset===k?" on":"")} onClick={()=>setPreset(k)}>
                  <span className="pname">{p.label}</span>
                  <span className="pblurb">{p.blurb}</span>
                </button>
              ))}
            </div>
            {preset === "custom" && (
              <div className="cyc-edit">
                <div className="cyc-row">
                  {Array.from({length: customLen}).map((_,i)=>(
                    <button key={i} className={"cyc-day"+(customOn[i]?" on":"")} onClick={()=>toggleCustom(i)} title={"Day "+(i+1)}>{i+1}</button>
                  ))}
                </div>
                <div className="cyc-len">
                  <span>Cycle: {customLen} days</span>
                  <input type="range" min="2" max="14" value={customLen} onChange={e=>setCustomLen(parseInt(e.target.value))} />
                </div>
                <p className="tap-hint" style={{marginTop:10}}>Tap a day to mark it a <b>work</b> day.</p>
              </div>
            )}
          </div>

          <div className="ctl">
            <label className="ctl-label">Rotation starts</label>
            <input type="date" className="datein" value={anchor} onChange={e=>setAnchor(e.target.value)} />
            <p className="tap-hint" style={{marginTop:10}}>Set this to the first day of an "on" block so the pattern lines up with reality.</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 className="mini-actions">
              {Object.keys(kidDays).length>0 && <button className="link-btn" onClick={clearKids}>Clear kid days</button>}
            </div>
          </div>
        </aside>

        <main className="panel cal">
          <PrintBrand toolName="Shift Parent OS" />
          <div className="cal-top">
            <div className="cal-month">
              <h2>{MONTHS[view.m]} {view.y}</h2>
              <span className="print-only" style={{fontFamily:"var(--mono)",fontSize:13,color:"var(--ink-500)"}}>{name} · {PRESETS[preset].label}</span>
            </div>
            <div className="cal-nav no-print">
              <button className="navb" onClick={()=>nav(-1)} aria-label="Previous month"><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>
              <button className="navb today" onClick={goToday}>Today</button>
              <button className="navb" onClick={()=>nav(1)} aria-label="Next month"><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>
          </div>

          <div className="dow-row">{DOW.map(d=><span key={d}>{d}</span>)}</div>
          <div className="cal-grid">
            {grid.map((date,i)=>{
              if(!date) return <div key={i} className="cell empty"></div>;
              const st = stateOf(date);
              const c = C[st];
              const key = ymd(date);
              const isToday = key===todayKey;
              const kids = !!kidDays[key];
              return (
                <button key={i} className={"cell"+(isToday?" today":"")} onClick={()=>toggleKid(date)}
                  style={{ background: c.bg, borderColor: st==="cover"?c.border:(isToday?c.fg:"transparent"), color: c.fg }}>
                  <span className="cd">{date.getDate()}</span>
                  <span className="cs">{c.label}</span>
                  {kids && <span className="kid" style={{background:c.fg}}></span>}
                </button>
              );
            })}
          </div>

          <div className="cal-foot">
            <div className="legend">
              <span className="lg"><i style={{background:C.work.bg, boxShadow:"inset 0 0 0 1px "+C.work.fg}}></i> Working</span>
              <span className="lg"><i style={{background:C.withyou.bg, boxShadow:"inset 0 0 0 1px "+C.withyou.fg}}></i> With you</span>
              <span className="lg"><i style={{background:C.cover.bg, boxShadow:"inset 0 0 0 1px "+C.cover.border}}></i> Needs cover</span>
              <span className="lg"><i style={{background:C.off.bg, boxShadow:"inset 0 0 0 1px "+C.off.fg}}></i> Off</span>
            </div>
            <div className="stats">
              <div className="stat"><div className="v">{monthStats.work}</div><div className="l">Work days</div></div>
              <div className="stat"><div className="v">{monthStats.kids}</div><div className="l">Days with kids</div></div>
              <div className={"stat"+(monthStats.cover?" alert":"")}><div className="v">{monthStats.cover}</div><div className="l">Need coverage</div></div>
            </div>
          </div>

          {monthStats.cover > 0 ? (
            <div className="cover">
              <h3>Coverage needed · {MONTHS[view.m]}</h3>
              <ul>
                {monthStats.coverList.map(d=>(
                  <li key={ymd(d)}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#b3760a" strokeWidth="2.2"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    You're <b>working</b> and have the kids
                    <span className="when">{DOW[d.getDay()]} {MONTHS[view.m].slice(0,3)} {d.getDate()}</span>
                  </li>
                ))}
              </ul>
            </div>
          ) : (
            <div className="cover-empty">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M20 6 9 17l-5-5" strokeLinecap="round" strokeLinejoin="round"/></svg>
              No clashes this month — every day you have the kids is a day off. Tap days to mark when you have them.
            </div>
          )}

          <p className="tap-hint no-print">Tip: tap any day to mark when you have the kids. Days that land on a shift turn amber — those are the ones to swap or arrange cover for.</p>
          <LeadNextStep
            captured={captured}
            title="Keep work shifts and parenting time together."
            body="Your shift plan is unlocked. CoHaven can help track changing work blocks, custody coverage, and swap planning without rebuilding the calendar."
          />
        </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 shift calendar to your email."
        subline="We'll email your schedule as a PDF — and unlock printing on this device."
      />
    </div>
  );
}

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