// GK App — main dashboard application.
const { analyzeMonth, seasonSeries, classDetail, fmt: fmtMoney, monthShort: mShort, monthLong: mLong } = window.GKAnalysis;

const GK_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "amberDollar": 1000,
  "amberPct": 25,
  "redDollar": 2500,
  "redPct": 50,
  "showGoodNews": true
}/*EDITMODE-END*/;

const REPORT_SLOTS = [
  { key: 'pl', name: 'Monthly P&L' },
  { key: 'ytd', name: 'YTD P&L' },
  { key: 'byClass', name: 'P&L by class' },
  { key: 'balance', name: 'Balance sheet' },
];

function App() {
  const [t, setTweak] = useTweaks(GK_TWEAK_DEFAULTS);
  const [state, setState] = React.useState(null);
  const [selected, setSelected] = React.useState(null);
  const [drill, setDrill] = React.useState(null);
  const [classDrill, setClassDrill] = React.useState(null);
  const [status, setStatus] = React.useState(null);
  const [toasts, setToasts] = React.useState([]);
  const [dragging, setDragging] = React.useState(false);
  const [archiveOpen, setArchiveOpen] = React.useState(false);
  const fileRef = React.useRef(null);

  // ---- init: load store, seed if empty ----
  React.useEffect(() => {
    (async () => {
      const s = GKStore.load();
      if (!s.seeded && Object.keys(s.months).length === 0) {
        setStatus('Reading the March & April reports…');
        try { await GKStore.seed(s); } catch (e) { console.warn(e); }
        setStatus(null);
      }
      setState(s);
      const keys = Object.keys(s.months).sort();
      if (keys.length) setSelected(keys[keys.length - 1]);
    })();
  }, []);

  const monthKeys = state ? Object.keys(state.months).sort().reverse() : [];
  const month = state && selected ? state.months[selected] : null;

  const thresholds = {
    amberDollar: t.amberDollar, amberPct: t.amberPct,
    redDollar: t.redDollar, redPct: t.redPct,
  };
  const analysis = React.useMemo(
    () => (month ? analyzeMonth(month, thresholds) : null),
    [month, t.amberDollar, t.amberPct, t.redDollar, t.redPct]
  );
  const series = React.useMemo(
    () => (state ? seasonSeries(state.months) : []),
    [state]
  );
  const drillData = React.useMemo(
    () => (month && drill ? window.GKAnalysis.drilldown(month, drill) : null),
    [month, drill]
  );

  const allSortedKeys = state ? Object.keys(state.months).sort() : [];
  const prevMonthKey = selected ? (() => { const i = allSortedKeys.indexOf(selected); return i > 0 ? allSortedKeys[i - 1] : null; })() : null;
  const prevMonth = prevMonthKey && state ? state.months[prevMonthKey] : null;
  const lastYearMonthKey = selected ? (() => {
    const parts = selected.split('-');
    return (Number(parts[0]) - 1) + '-' + parts[1];
  })() : null;
  const lastYearMonth = lastYearMonthKey && state ? state.months[lastYearMonthKey] : null;

  const classDetailData = React.useMemo(
    () => (month && classDrill ? classDetail(month, classDrill, prevMonth, lastYearMonth, lastYearMonthKey) : null),
    [month, classDrill, prevMonth, lastYearMonth, lastYearMonthKey]
  );

  const toggleClassDrill = (name) => setClassDrill(classDrill === name ? null : name);
  React.useEffect(() => { setDrill(null); setClassDrill(null); }, [selected]);
  const toggleDrill = (kind) => setDrill(drill === kind ? null : kind);

  // ---- file ingest ----
  async function handleFiles(files) {
    if (!files || !files.length || !state) return;
    setStatus('Reading ' + files.length + ' file' + (files.length > 1 ? 's' : '') + '…');
    const next = { ...state, months: { ...state.months }, docs: { ...state.docs }, archive: [...(state.archive || [])] };
    const results = await GKStore.ingestFiles(next, [...files]);
    setState(next);
    setStatus(null);
    setToasts(results);
    setTimeout(() => setToasts([]), 9000);
    const okMonths = Object.keys(next.months).sort();
    if (okMonths.length) setSelected(okMonths[okMonths.length - 1]);
  }

  React.useEffect(() => {
    const over = (e) => { e.preventDefault(); setDragging(true); };
    const leave = (e) => { if (!e.relatedTarget) setDragging(false); };
    const drop = (e) => {
      e.preventDefault(); setDragging(false);
      handleFiles(e.dataTransfer.files);
    };
    window.addEventListener('dragover', over);
    window.addEventListener('dragleave', leave);
    window.addEventListener('drop', drop);
    return () => {
      window.removeEventListener('dragover', over);
      window.removeEventListener('dragleave', leave);
      window.removeEventListener('drop', drop);
    };
  });

  function resetSample() {
    if (!confirm('Replace saved data with the bundled March & April sample reports?')) return;
    const fresh = { months: {}, docs: {}, archive: [], seeded: false };
    setStatus('Reloading sample reports…');
    GKStore.seed(fresh).then(() => {
      setState(fresh);
      const keys = Object.keys(fresh.months).sort();
      setSelected(keys[keys.length - 1] || null);
      setStatus(null);
    });
  }

  if (!state) return <div className="boot">Loading…</div>;

  const have = month ? REPORT_SLOTS.filter((s) => month[s.key]) : [];
  const missing = month ? REPORT_SLOTS.filter((s) => !month[s.key]) : [];

  return (
    <div>
      <div className="app-screen">
        <header className="topbar">
          <div className="brand">
            <div className="brand-mark">
              <img src="assets/golf-kenosee-logo.png" alt="Golf Kenosee logo"></img>
            </div>
            <div>
              <div className="brand-name">Golf Kenosee</div>
              <div className="brand-sub">Board Financial Dashboard</div>
            </div>
          </div>
          <div className="topbar-right">
            <div className="month-pills">
              {monthKeys.map((k) => (
                <button key={k} className={'pill' + (k === selected ? ' active' : '')} onClick={() => setSelected(k)}>
                  {mShort(k)}
                </button>
              ))}
            </div>
            <button className="btn btn-ghost" onClick={() => fileRef.current && fileRef.current.click()}>
              Add this month's files
            </button>
            <button
              type="button"
              className={'btn btn-ghost menu-btn' + (archiveOpen ? ' active' : '')}
              onClick={() => setArchiveOpen(true)}
              aria-label="Open past reports"
            >
              <span className="menu-icon" aria-hidden="true"><span></span><span></span><span></span></span>
              <span>Past Reports</span>
            </button>
            <button className="btn btn-solid" onClick={() => window.print()}>Print one-pager</button>
            <input
              ref={fileRef} type="file" multiple accept=".pdf,.docx,.doc" style={{ display: 'none' }}
              onChange={(e) => { handleFiles(e.target.files); e.target.value = ''; }}
            ></input>
          </div>
        </header>

        {status ? <div className="status-bar">{status}</div> : null}

        {toasts.length ? (
          <div className="toasts">
            {toasts.map((r, i) => (
              <div key={i} className={'toast ' + (r.ok ? 'ok' : 'err')}>
                <strong>{r.file}</strong> — {r.what}
              </div>
            ))}
          </div>
        ) : null}

        {!month ? (
          <div className="empty-state">
            <h2>Drop this month's board package anywhere on this page</h2>
            <p>The four QuickBooks PDFs (P&L, P&L YTD, P&L by class, balance sheet) plus the agenda and minutes Word files. Everything is read locally in your browser — nothing is uploaded.</p>
          </div>
        ) : (
          <main className="content" data-screen-label={'Dashboard ' + mLong(selected)}>
            <div className="month-head">
              <h1 className="month-title">{mLong(selected)}</h1>
              <div className="month-meta">
                {have.length} of 4 reports in
                {missing.length ? <span className="missing"> · missing: {missing.map((m) => m.name).join(', ')}</span> : null}
                <span className="dot-sep">·</span> fiscal year began December
              </div>
            </div>

            <section className="panel">
              <h2 className="panel-h">Meeting prep</h2>
              <MeetingPrep agenda={state.docs.agenda} minutes={state.docs.minutes}></MeetingPrep>
            </section>

            <section className="kpi-grid">
              <KpiCard title={mShort(selected) + ' net income'} value={analysis.kpis.monthNet.cur} prior={analysis.kpis.monthNet.prior} active={drill === 'monthNet'} onClick={() => toggleDrill('monthNet')}></KpiCard>
              <KpiCard title="YTD net income" value={analysis.kpis.ytdNet.cur} prior={analysis.kpis.ytdNet.prior} active={drill === 'ytdNet'} onClick={() => toggleDrill('ytdNet')}></KpiCard>
              <KpiCard title={mShort(selected) + ' revenue'} value={analysis.kpis.monthIncome.cur} prior={analysis.kpis.monthIncome.prior} active={drill === 'monthIncome'} onClick={() => toggleDrill('monthIncome')}></KpiCard>
              <KpiCard title={mShort(selected) + ' expenses'} value={analysis.kpis.monthExpense.cur} prior={analysis.kpis.monthExpense.prior} invert={true} active={drill === 'monthExpense'} onClick={() => toggleDrill('monthExpense')}></KpiCard>
              <KpiCard title="Cash & equivalents" value={analysis.kpis.cash.cur} prior={analysis.kpis.cash.prior} active={drill === 'cash'} onClick={() => toggleDrill('cash')}></KpiCard>
            </section>

            {drillData ? (
              <section>
                <DrillPanel drill={drillData} onClose={() => setDrill(null)}></DrillPanel>
              </section>
            ) : null}

            <section className="panel">
              <h2 className="panel-h">By operation — {mShort(selected)}</h2>
              <div className="class-grid">
                {analysis.classes.map((c) => (
                  <ClassCard
                    key={c.name}
                    cls={c}
                    seasonal={c.name === 'Club 19 Restaurant'}
                    onClick={() => toggleClassDrill(c.name)}
                    active={classDrill === c.name}
                  ></ClassCard>
                ))}
              </div>
              {classDetailData ? (
                <ClassDrillPanel
                  detail={classDetailData}
                  onClose={() => setClassDrill(null)}
                ></ClassDrillPanel>
              ) : null}
              {analysis.classes.some((c) => c.name === 'Club 19 Restaurant') ? (
                <div className="panel-foot">Club 19 runs May–September; early-season months carry wages and prep costs against little revenue.</div>
              ) : null}
            </section>

            <section className="two-col">
              <div className="panel">
                <h2 className="panel-h">Needs a look <span className="count-chip">{analysis.flags.attention.length}</span></h2>
                <div className="flag-list">
                  {analysis.flags.attention.length === 0 ? <div className="empty-note">Nothing crosses the flag thresholds. Quiet month.</div> : null}
                  {analysis.flags.attention.map((f) => <FlagCard key={f.label + f.scope} flag={f}></FlagCard>)}
                </div>
              </div>
              <div className="panel panel-questions">
                <h2 className="panel-h">Questions to bring</h2>
                <QuestionsList questions={analysis.questions}></QuestionsList>
              </div>
            </section>

            <section className="three-col">
              {t.showGoodNews ? (
                <div className="panel">
                  <h2 className="panel-h">Good news</h2>
                  <div className="flag-list compact">
                    {analysis.flags.good.length === 0 ? <div className="empty-note">No favorable swings above threshold.</div> : null}
                    {analysis.flags.good.slice(0, 5).map((f) => <FlagCard key={f.label + f.scope} flag={f}></FlagCard>)}
                  </div>
                </div>
              ) : null}
              <div className="panel">
                <h2 className="panel-h">Balance sheet watch</h2>
                <BalanceWatch items={analysis.balanceWatch}></BalanceWatch>
              </div>
              <div className="panel">
                <h2 className="panel-h">Season tracker <span className="panel-sub">net income by month</span></h2>
                <SeasonChart series={series}></SeasonChart>
              </div>
            </section>

            <footer className="app-foot">
              <span>Files are parsed locally in your browser and saved on this computer — nothing is uploaded.</span>
              <button className="ghost-btn" onClick={resetSample}>Reset to sample data</button>
            </footer>
          </main>
        )}
      </div>

      {dragging ? (
        <div className="drop-overlay">
          <div className="drop-box">Drop the board package here<br /><span>PDFs + Word files, any order</span></div>
        </div>
      ) : null}

      <ArchiveDrawer
        open={archiveOpen}
        archive={state.archive || []}
        onClose={() => setArchiveOpen(false)}
      ></ArchiveDrawer>

      {month && analysis ? <PrintSheet monthKey={selected} analysis={analysis} agenda={state.docs.agenda}></PrintSheet> : null}

      <TweaksPanel>
        <TweakSection label="Amber flag (notable)"></TweakSection>
        <TweakSlider label="Min dollar swing" value={t.amberDollar} min={250} max={5000} step={250} unit="$" onChange={(v) => setTweak('amberDollar', v)}></TweakSlider>
        <TweakSlider label="Min % swing" value={t.amberPct} min={10} max={100} step={5} unit="%" onChange={(v) => setTweak('amberPct', v)}></TweakSlider>
        <TweakSection label="Red flag (serious)"></TweakSection>
        <TweakSlider label="Min dollar swing" value={t.redDollar} min={1000} max={15000} step={500} unit="$" onChange={(v) => setTweak('redDollar', v)}></TweakSlider>
        <TweakSlider label="Min % swing" value={t.redPct} min={25} max={200} step={5} unit="%" onChange={(v) => setTweak('redPct', v)}></TweakSlider>
        <TweakSection label="Display"></TweakSection>
        <TweakToggle label="Show good news" value={t.showGoodNews} onChange={(v) => setTweak('showGoodNews', v)}></TweakToggle>
      </TweaksPanel>
    </div>
  );
}

pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
ReactDOM.createRoot(document.getElementById('root')).render(<App></App>);
