// ============================================================
// TANK'S TRADING DESK — plans-app.jsx
// Pre-Market Plan ARCHIVE. Lets members browse past daily plans
// instead of digging through Discord.
//
// Reuse, don't rebuild: an archived day renders through the SAME
// homepage components (PremarketPlanHero + MarketDataSheet from
// home-sections.jsx) — we just point window.__resources.premarket
// at that day's snapshot before the component mounts, so the look
// is byte-identical to the index page's Daily Plan section.
//
// Live-only modules (open positions / live TradingView frame) are
// NOT part of a historical snapshot, so they're hidden via CSS in
// Past Plans.html and performance is pointed at an empty file.
// ============================================================

const { useState: paState, useEffect: paEffect } = React;

const PA_VERDICT = {
  bullish: { tag: 'Bull', cls: 'bull' },
  bearish: { tag: 'Bear', cls: 'bear' },
  neutral: { tag: 'Neutral', cls: 'neut' }
};
const paBias = (v) => PA_VERDICT[v] || PA_VERDICT.neutral;

// short label e.g. "Thu · 18 Jun" from "Thu · 18 Jun 2026"
const paShort = (label) => (label || '').replace(/\s+\d{4}$/, '');

// Locally-archived plans (written from the homepage "Archive today's plan"
// admin action) live in localStorage — the sole source going forward.
const paLocalIndex = () => {try {return JSON.parse(localStorage.getItem('18c:archivedIndex:v1') || '[]');} catch (e) {return [];}};
const paLocalSnap = (date) => {try {return (JSON.parse(localStorage.getItem('18c:archivedPlans:v1') || '{}') || {})[date] || null;} catch (e) {return null;}};
const paMergeIndex = (idx) => {
  const byDate = {};
  (idx && idx.plans || []).forEach((p) => {byDate[p.date] = p;});
  paLocalIndex().forEach((p) => {byDate[p.date] = { ...p, local: true };});
  const plans = Object.values(byDate).sort((a, b) => a.date < b.date ? 1 : -1);
  return { ...(idx || {}), plans, count: plans.length, latest: plans[0] && plans[0].date };
};

// ============================================================
// ARCHIVED PLANS — the going-forward archive. Admin publishes a plan
// from the homepage (stored server-side via the Worker API); this
// section lists every published plan and lets ANY visitor download
// its PDF, generated on demand from the shared snapshot.
// ============================================================
const paDateLabel = (date) => {
  const m = (date || '').match(/(\d{4})-(\d{2})-(\d{2})/);
  if (!m) return date || '';
  const y = +m[1],mo = +m[2],d = +m[3];
  const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],MO = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return `${WD[new Date(Date.UTC(y, mo - 1, d)).getUTCDay()]} \u00b7 ${d} ${MO[mo - 1]} ${y}`;
};

function PdfArchive() {
  const [rows, setRows] = paState([]);
  const [loading, setLoading] = paState(true);

  paEffect(() => {
    let live = true;
    if (!window.PlanAPI) {setLoading(false);return;}
    // Candidate dates: the shared session manifest PLUS recent calendar days
    // (so plans published from the desk today — not yet in the backend
    // manifest — still appear). Each is probed and kept only if published.
    const recent = [];
    const now = new Date();
    for (let i = 0; i < 60; i++) {
      const d = new Date(now.getTime() - i * 86400000);
      recent.push(d.toISOString().slice(0, 10));
    }
    fetch('data/plans/index.json').then((r) => r.ok ? r.json() : null).
    then((idx) => {
      const manifest = (idx && idx.plans || []).map((p) => p.date).filter(Boolean);
      const dates = Array.from(new Set([...recent, ...manifest]));
      return Promise.all(dates.map((d) => window.PlanAPI.getPlan(d).then((p) => p && p.render ? { date: d, plan: p } : null)));
    }).
    then((res) => {
      if (!live) return;
      const kept = (res || []).filter(Boolean).sort((a, b) => a.date < b.date ? 1 : -1);
      setRows(kept);setLoading(false);
    }).
    catch(() => {if (live) setLoading(false);});
    return () => {live = false;};
  }, []);

  const download = (row) => {
    const ok = window.PlanAPI.openPdf(row.plan.render, row.plan);
    if (!ok) alert('Pop-up blocked \u2014 allow pop-ups to download the plan PDF.');
  };

  return (
    <section className="pla-listsec pdfsec">
      <div className="pla-listsec-in">
        <div className="pla-listhead">
          <span className="pla-listhead-l">Archived Plan</span>
          <span className="pla-listhead-r"></span>
        </div>
        {loading ?
        <p className="pla-state pdf-empty">Loading published plans\u2026</p> :
        rows.length ?
        <div className="pla-grid pdf-grid">
            {rows.map((row) => {
            const r = row.plan.render || {},meta = r.meta || {};
            const head = meta.composite && meta.composite.label || '';
            return (
              <div className="pla-card pdf-card" key={row.date}>
                  <div className="pla-card-top">
                    <span className="pla-card-date">{meta.session_label || paDateLabel(row.date)}</span>
                    <span className="pla-chip bull">Published</span>
                  </div>
                  {head ? <div className="pdf-file">{head}</div> : <div className="pdf-file">Daily plan \u00b7 {row.date}</div>}
                  <div className="pla-card-foot">
                    <button className="pdf-open" onClick={() => download(row)}>Download PDF <span className="arr">↓</span></button>
                  </div>
                </div>);

          })}
          </div> :
        <p className="pla-state pdf-empty">No published plans yet. Publish one from the trading desk to see it here.</p>}
      </div>
    </section>);

}

// ============================================================
// ARCHIVE INDEX — reverse-chronological grid of session cards
// ============================================================
function ArchiveIndex({ index, onOpen }) {
  const plans = index.plans || [];
  return (
    <main className="pla-wrap">
      <header className="pla-hero">
        <div className="pla-hero-in">
          <a className="sb-back" href="index.html"><span className="arr">←</span> Back to the trading desk</a>
          <p className="pla-eb">Plan Archive</p>
          <h1 className="pla-h">Every plan, <em>on the record.</em></h1>
          <p className="pla-lead">
            The full pre-market plan is published before the bell, every session — then it lives here. Browse any past day's bias read, levels and sector map exactly as it was posted. <b>{index.count} sessions</b> archived, newest first.
          </p>
        </div>
      </header>

      <PdfArchive />

      <section className="pla-listsec">
        <div className="pla-listsec-in">
          <div className="pla-listhead">
            <span className="pla-listhead-l">Archived Plan before 15 Jul 2026</span>
            <span className="pla-listhead-r"></span>
          </div>
          <div className="pla-grid">
            {plans.map((p) => {
              const b = paBias(p.verdict);
              return (
                <button className="pla-card" key={p.date} onClick={() => onOpen(p.date)}>
                  <div className="pla-card-top">
                    <span className="pla-card-date">{paShort(p.label)}</span>
                    <span className={'pla-chip ' + b.cls}>{p.band}</span>
                  </div>
                  <div className="pla-card-h">{p.headline}</div>
                  {p.summary ? <p className="pla-card-sum">{p.summary}</p> : <p className="pla-card-sum muted">Bias read &amp; sector map archived for this session.</p>}
                  <div className="pla-card-foot">
                    <span className="pla-rb">{p.rulebook}</span>
                    <span className={'pla-comp ' + (p.has_tiers ? 'full' : 'sum')}>{p.has_tiers ? 'Full plan' : 'Summary'}</span>
                    <span className="pla-go">View plan <span className="arr">→</span></span>
                  </div>
                </button>);
            })}
          </div>
        </div>
      </section>
    </main>);
}

// ============================================================
// ARCHIVE DETAIL — one archived day, rendered through the
// homepage plan components. Date nav (prev/next/picker/back).
// ============================================================
function ArchiveDetail({ index, date, onOpen, onBack }) {
  const plans = index.plans || [];
  const i = plans.findIndex((p) => p.date === date);
  const row = plans[i] || {};
  // newest-first list: i-1 is the NEXT (newer) session, i+1 is PREVIOUS (older)
  const newer = i > 0 ? plans[i - 1] : null;
  const older = i >= 0 && i < plans.length - 1 ? plans[i + 1] : null;

  // Point the shared resources at THIS day's snapshot before the
  // homepage components mount. Backend days load their file; locally
  // archived days are served from localStorage via a blob URL.
  let premarketUrl = row.file;
  if (row.local) {
    const snap = paLocalSnap(date);
    if (snap) premarketUrl = URL.createObjectURL(new Blob([JSON.stringify(snap)], { type: 'application/json' }));
  }
  window.__resources = { premarket: premarketUrl, performance: 'data/plans/_noperf.json' };

  return (
    <main className="pla-detail">
      <div className="pla-navbar">
        <div className="pla-navbar-in">
          <button className="pla-allbtn" onClick={onBack}>All plans</button>
          <div className="pla-nav-center">
            <button className="pla-step" onClick={() => older && onOpen(older.date)} disabled={!older} aria-label="Older session">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6" /></svg>
            </button>
            <label className="pla-picker">
              <span className="pla-picker-eb">Session</span>
              <select className="pla-select" value={date} onChange={(e) => onOpen(e.target.value)}>
                {plans.map((p) => <option key={p.date} value={p.date}>{paShort(p.label)} · {p.band}</option>)}
              </select>
            </label>
            <button className="pla-step" onClick={() => newer && onOpen(newer.date)} disabled={!newer} aria-label="Newer session">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6" /></svg>
            </button>
          </div>
        </div>
      </div>

      <div className={'pla-planwrap ' + (row.has_tiers ? 'has-tiers' : 'summary-only')}>
        {!row.has_tiers ?
        <div className="pla-archnote">
            <span className="pla-archnote-dot" aria-hidden="true" />
            This early session predates the structured tier plan — showing the published bias read, allowed/not-allowed and sector map. Full level &amp; tier plans begin 10 Jun 2026.
          </div> : null}
        <PremarketPlanHero key={'ph-' + date} staleSim="ready" onJoin={() => {location.href = 'index.html#cta';}} />
        <MarketDataSheet key={'md-' + date} />
      </div>
    </main>);
}

// ============================================================
// APP — manifest load + ?d= routing
// ============================================================
function PlansApp() {
  const [index, setIndex] = paState(null);
  const [err, setErr] = paState(false);
  const [date, setDate] = paState(() => new URLSearchParams(location.search).get('d'));

  paEffect(() => {
    fetch('data/plans/index.json').then((r) => r.ok ? r.json() : Promise.reject(r.status)).
    then((idx) => setIndex(paMergeIndex(idx))).
    catch(() => setIndex(paMergeIndex(null)));
  }, []);
  paEffect(() => {
    const onPop = () => setDate(new URLSearchParams(location.search).get('d'));
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const open = (d) => {
    const u = new URL(location.href);
    u.searchParams.set('d', d);
    history.pushState({}, '', u);
    setDate(d);
    window.scrollTo(0, 0);
  };
  const back = () => {
    const u = new URL(location.href);
    u.searchParams.delete('d');
    history.pushState({}, '', u);
    setDate(null);
    window.scrollTo(0, 0);
  };

  if (err) return <main className="pla-wrap"><div className="pla-state">Couldn't load the plan archive. Please try again.</div></main>;
  if (!index) return <main className="pla-wrap"><div className="pla-state">Loading the plan archive…</div></main>;

  const valid = date && (index.plans || []).some((p) => p.date === date);
  return valid ?
  <ArchiveDetail index={index} date={date} onOpen={open} onBack={back} /> :
  <ArchiveIndex index={index} onOpen={open} />;
}

ReactDOM.createRoot(document.getElementById('plans-root')).render(<PlansApp />);