/* Seasons: records, picker with proof, calendar, priority, auction tie-in, per-season results. */
const RAIL_IDS_FOR_BOOST = ['trending', 'bestsellers', 'upcoming', 'new', 'exclusives', 'books', 'vinyl', 'sports', 'music', 'movies_tv', 'under100', 'historic', 'for_you', 'live'];
const STATUS_KIND = { live: 'good', scheduled: 'navy', ended: '', draft: 'warn', off: 'bad' };

function SeasonsPage() {
  const toast = useToast(); const { assets, reloadAssets, segments, refreshLive } = useDraft();
  const [list, setList] = useState([]); const [today, setToday] = useState(''); const [edit, setEdit] = useState(null); const [view, setView] = useState('list'); const [groups, setGroups] = useState([]); const [results, setResults] = useState(null);
  const load = async () => { const r = await api('/seasons'); if (r.data) { setList(r.data); setToday(r.today); } const g = await api('/auction-groups'); if (g.data) setGroups(g.data); };
  useEffect(() => { load(); api('/analytics/overview?from=2020-01-01').then(r => r.data && setResults(r.data.seasons)); }, []);
  const save = async (s) => {
    const r = s.id ? await api(`/seasons/${s.id}`, { method: 'PUT', body: s }) : await api('/seasons', { method: 'POST', body: s });
    if (r.error) return toast(r.error, 'bad');
    toast(`Saved ${r.data.name}. Seasons go live from their window, no publish needed.`); setEdit(null); load(); refreshLive && refreshLive();
  };
  const del = async (s) => { if (!confirm(`Delete season “${s.name}”?`)) return; await api(`/seasons/${s.id}`, { method: 'DELETE' }); load(); };
  const res = (key) => (results || []).find(r => r.key === key);
  return <div>
    <div className="topbar"><h1>Seasons</h1><span className="muted">Store time is Central; today is {today}. The server decides which seasons are live, so every visitor agrees.</span><div className="right row"><div className="tabs row"><button className={'tab ' + (view === 'list' ? 'active' : '')} onClick={() => setView('list')}>List</button><button className={'tab ' + (view === 'cal' ? 'active' : '')} onClick={() => setView('cal')}>Calendar</button></div><button className="btn primary" onClick={() => setEdit({ key: '', name: '', repeat_yearly: true, priority: 50, query: {}, boosts: {}, hero: null })}>+ New season</button></div></div>
    {view === 'list' ? <div className="card tight"><Table cols={[
      { k: 'status', l: 'Status', f: s => <Pill kind={STATUS_KIND[s.status]}>{s.status}</Pill> },
      { k: 'name', l: 'Season', f: s => <div><b>{s.name}</b><div className="muted small">{s.title || '—'} · <span className="mono">{s.key}</span></div></div> },
      { k: 'window', l: 'Window', f: s => s.auction_group_id ? <span>Tied to sale #{s.auction_group_id}</span> : <span>{s.start_date} → {s.end_date}{s.repeat_yearly ? ' · yearly' : ' · one-off'}</span> },
      { k: 'priority', l: 'Priority', num: true },
      { k: 'results', l: 'Results (all time)', f: s => { const r = res(s.key); return r ? <span className="small">{fmt(r.views)} views · {fmt(r.clicks)} clicks · {pct(r.ctr)}{r.revenue ? ' · ' + money(r.revenue) : ''}</span> : <span className="muted small">no data yet</span>; } },
      { k: 'act', l: '', f: s => <div className="row"><button className="btn sm" onClick={() => setEdit(s)}>Edit</button><button className="btn sm danger" onClick={() => del(s)}>Delete</button></div> },
    ]} rows={list} /></div> : <Calendar />}
    {edit && <SeasonForm s={edit} onSave={save} onClose={() => setEdit(null)} groups={groups} assets={assets} reloadAssets={reloadAssets} segments={segments} />}
  </div>;
}
function SeasonForm({ s: init, onSave, onClose, groups, assets, reloadAssets, segments }) {
  const [s, set] = useState({ ...init, hero: init.hero || null }); const up = (p) => set(x => ({ ...x, ...p }));
  const hero = s.hero || {}; const setHero = (p) => up({ hero: { ...hero, ...p } });
  const segOpts = (segments || []).map(x => x.key);
  return <Modal title={s.id ? `Edit season: ${s.name}` : 'New season'} wide onClose={onClose} footer={<><button className="btn" onClick={onClose}>Cancel</button><button className="btn primary" onClick={() => onSave(s)} disabled={!s.name || !s.key}>Save season</button></>}>
    <div className="stack">
      <div className="grid3"><Field label="Name"><Text value={s.name} onChange={v => up({ name: v, key: s.id ? s.key : slug(v) })} /></Field><Field label="Key" hint="Stable, used in analytics"><Text value={s.key} onChange={v => up({ key: slug(v) })} disabled={!!s.id} /></Field><Field label={`Priority: ${s.priority}`} hint="Highest active season leads"><input type="range" min="1" max="100" value={s.priority} onChange={e => up({ priority: Number(e.target.value) })} /></Field></div>
      <div className="grid4"><Field label="Start (store time)"><input type="date" value={s.start_date || ''} onChange={e => up({ start_date: e.target.value })} /></Field><Field label="End (inclusive)"><input type="date" value={s.end_date || ''} onChange={e => up({ end_date: e.target.value })} /></Field><Field label="Repeat"><Toggle on={s.repeat_yearly} onChange={v => up({ repeat_yearly: v })} label={s.repeat_yearly ? 'Every year' : 'One-off'} /></Field><Field label="Force off"><Toggle on={s.force_status === 'off'} onChange={v => up({ force_status: v ? 'off' : null })} label={s.force_status === 'off' ? 'Off' : 'Follows the window'} /></Field></div>
      <Field label="Auction tie-in" hint="Optional: active while that sale's lots are live, no dates typed."><select value={s.auction_group_id || ''} onChange={e => up({ auction_group_id: e.target.value ? Number(e.target.value) : null })}><option value="">None</option>{groups.map(g => <option key={g.id} value={g.id}>{g.name} · {g.lots} lots{g.live ? ` · ${g.live} live` : ''}</option>)}</select></Field>
      <div className="grid2"><Field label="Rail title" count={(s.title || '').length} max={48}><Text value={s.title} onChange={v => up({ title: v })} /></Field><Field label="Rail subtitle" count={(s.subtitle || '').length} max={90}><Text value={s.subtitle} onChange={v => up({ subtitle: v })} /></Field></div>
      <Field label="Products" hint="Built with the picker. Fewer than 8 in stock shows a warning."><QueryBuilder value={s.query} onChange={q => up({ query: q })} /></Field>
      <Field label="Boosts while the season runs" hint="Adds to a rail's base weight"><div className="grid4">{RAIL_IDS_FOR_BOOST.map(id => <div className="row" key={id}><span className="small" style={{ width: 80 }}>{id}</span><input type="range" min="-30" max="30" value={(s.boosts || {})[id] || 0} onChange={e => up({ boosts: { ...(s.boosts || {}), [id]: Number(e.target.value) } })} /><span className="small mono" style={{ width: 28 }}>{(s.boosts || {})[id] || 0}</span></div>)}</div></Field>
      <div className="card tight"><h3>Hero override (optional)</h3><div className="grid3" style={{ marginTop: 8 }}>
        <Field label="Kicker"><Text value={hero.kicker} onChange={v => setHero({ kicker: v })} /></Field><Field label="Subtitle"><Text value={hero.sub} onChange={v => setHero({ sub: v })} /></Field><Field label="Art"><AssetPicker value={hero.asset_id} onChange={v => setHero({ asset_id: v })} assets={assets} reload={reloadAssets} /></Field></div>
        <Field label="Applies to arrivals" hint="Empty = every arrival"><div className="row wrap">{['default', 'returning', 'social', 'email', 'member', 'live'].map(v => <label key={v} className="chip"><input type="checkbox" checked={(hero.variants || []).includes(v)} onChange={e => setHero({ variants: e.target.checked ? [...(hero.variants || []), v] : (hero.variants || []).filter(x => x !== v) })} /> {v}</label>)}</div></Field></div>
      <div className="grid3"><Field label="Share image (Open Graph)"><AssetPicker value={s.og_asset_id} onChange={v => up({ og_asset_id: v })} assets={assets} reload={reloadAssets} /></Field><Field label="Season URL slug" hint="For the season page project (later), e.g. halloween"><Text value={s.url_slug} onChange={v => up({ url_slug: slug(v) })} /></Field>
        <Field label="Target"><div className="row wrap"><span className="small muted">show:</span><SegPicker options={segOpts} value={(s.target_segments || {}).show || []} onChange={l => up({ target_segments: { ...(s.target_segments || {}), show: l } })} /><span className="small muted">hide:</span><SegPicker options={segOpts} value={(s.target_segments || {}).hide || []} onChange={l => up({ target_segments: { ...(s.target_segments || {}), hide: l } })} /></div></Field></div>
    </div>
  </Modal>;
}
function Calendar() {
  const [year, setYear] = useState(new Date().getFullYear()); const [d, setD] = useState(null);
  useEffect(() => { api(`/seasons/calendar?year=${year}`).then(r => r.data && setD(r.data)); }, [year]);
  if (!d) return <div className="card muted">Loading…</div>;
  const pos = (date) => { const t = (new Date(date + 'T00:00:00Z') - new Date(`${year}-01-01T00:00:00Z`)) / 864e5; const days = (new Date(`${year + 1}-01-01T00:00:00Z`) - new Date(`${year}-01-01T00:00:00Z`)) / 864e5; return Math.max(0, Math.min(100, 100 * t / days)); };
  const lanes = []; const sorted = d.bars.slice().sort((a, b) => a.start.localeCompare(b.start));
  sorted.forEach(b => { let li = lanes.findIndex(l => l.every(x => x.end < b.start || x.start > b.end)); if (li < 0) { lanes.push([]); li = lanes.length - 1; } lanes[li].push(b); });
  return <div className="card"><div className="row" style={{ marginBottom: 10 }}><button className="btn sm" onClick={() => setYear(year - 1)}>‹</button><b>{year}</b><button className="btn sm" onClick={() => setYear(year + 1)}>›</button><span className="muted small">Seasons in navy, auction sales in gold, live outlined green. Overlaps are visible before they happen.</span></div>
    <div className="cal"><div className="months">{['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].map(m => <div key={m}>{m}</div>)}</div>
      <div style={{ position: 'relative' }}>{lanes.map((lane, i) => <div className="lane" key={i}>{lane.map(b => <div key={b.key + b.start} className={'bar ' + (b.kind === 'auction' ? 'auction' : '') + (b.status === 'live' ? ' live' : '') + (b.status === 'off' ? ' off' : '')} style={{ left: pos(b.start) + '%', width: Math.max(1.2, pos(b.end) - pos(b.start) + 0.3) + '%' }} title={`${b.name}: ${b.start} → ${b.end}${b.priority ? ' · priority ' + b.priority : ''}`}>{b.name}</div>)}</div>)}
        {String(d.today).startsWith(String(year)) && <div className="today" style={{ left: pos(d.today) + '%' }} />}</div></div></div>;
}
