/* global React, Sparkline, MonoLabel, SectionLabel, StatusTag, IraqMap */
const { useMemo: useM } = React;

// ─── Overview Page ─────────────────────────────────────────────────
// Mirrors the real dashboard: editorial lead figure + hairline fact rail
// (deliberately NOT a uniform KPI stat-card grid — DESIGN.md §7 bans it).
function PageOverview({ state, setState }) {
  const movieById = useM(() => Object.fromEntries(state.movies.map(m => [m.id, m])), [state.movies]);
  const branchById = useM(() => Object.fromEntries(state.branches.map(b => [b.id, b])), [state.branches]);
  const liveShowtimes = useM(() => state.showtimes.filter(s => s.status !== 'cancelled'), [state.showtimes]);
  const upcoming = useM(() => [...liveShowtimes].sort((a, b) => a.start - b.start).slice(0, 8), [liveShowtimes]);
  const balanced = state.ledger.debits === state.ledger.credits;
  const user = state.user;
  const today = new Date();
  const timeOfDay = () => {
    const h = today.getHours();
    if (h < 5) return 'night'; if (h < 12) return 'morning'; if (h < 17) return 'afternoon'; return 'evening';
  };
  const usdApprox = Math.round(state.ledger.revenueIqd / state.fxRate);

  return (
    <div style={{display:'flex', flexDirection:'column', gap: 40}}>
      {/* Header */}
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end'}}>
        <div>
          <SectionLabel>Operations Overview</SectionLabel>
          <h1 style={{fontFamily:'var(--font-display)', fontSize: 34, fontWeight: 700, letterSpacing:'-0.025em', lineHeight: 1.1, color:'var(--ink-999)', margin:'8px 0 0'}}>
            Good {timeOfDay()}, {user.nameEn.split(' ')[0]}.
          </h1>
        </div>
        <MonoLabel style={{color:'var(--ink-700)'}}>
          {today.toLocaleDateString('en-IQ', {weekday:'long', month:'long', day:'numeric'})} · {user.role.replace('_', ' ').toUpperCase()}
        </MonoLabel>
      </div>

      {/* Lead figure + fact rail */}
      <div style={{display:'grid', gridTemplateColumns:'minmax(0,1.05fr) minmax(0,0.95fr)', gap: 32}}>
        <div className="cos-card-elevated">
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap: 12}}>
            <SectionLabel>Gross takings · today</SectionLabel>
            <Sparkline data={state.revenueSpark} width={108} height={30} stroke="#c6a15b"/>
          </div>
          <p style={{margin:'14px 0 0', fontSize: 52, fontWeight: 700, letterSpacing:'-0.03em', lineHeight: 1, color:'var(--ink-999)', fontVariantNumeric:'tabular-nums'}}>
            {state.ledger.revenueIqd.toLocaleString()}
            <span style={{fontFamily:'var(--font-mono)', fontSize: 16, fontWeight: 500, color:'var(--accent-gold)', marginInlineStart: 10, letterSpacing:'0.08em'}}>IQD</span>
          </p>
          <p className="cos-mono" style={{margin:'10px 0 0'}}>≈ ${usdApprox.toLocaleString()} at today's rate</p>
        </div>

        <div className="cos-card" style={{display:'flex', flexDirection:'column', justifyContent:'center', padding:'12px 24px'}}>
          <FactRow label="Bookings today" value={String(state.ledger.todayBookings)} spark={state.bookingsSpark}/>
          <div className="cos-hairline"/>
          <FactRow label="Upcoming shows" value={String(liveShowtimes.length)}/>
          <div className="cos-hairline"/>
          <FactRow label="FX rate · per 1 USD" value={state.fxRate.toLocaleString()} href="#fx"/>
          <div className="cos-hairline"/>
          <FactRow
            label="Ledger integrity"
            value={balanced ? 'Balanced' : 'Imbalance'}
            dot={balanced ? 'var(--ok)' : 'var(--err)'}
            valueColor={balanced ? 'var(--ok)' : 'var(--err)'}
          />
        </div>
      </div>

      {/* Branches + Map */}
      <div style={{display:'grid', gridTemplateColumns:'1.4fr 1fr', gap: 24}}>
        <div className="cos-card" style={{padding: 0, overflow:'hidden'}}>
          <div style={{padding:'20px 24px', borderBottom:'1px solid var(--ink-400)'}}>
            <SectionLabel>Branches</SectionLabel>
            <h2 style={{fontFamily:'var(--font-display)', fontSize: 18, fontWeight: 600, margin:'6px 0 0', color:'var(--ink-999)'}}>
              {state.branches.length} locations
            </h2>
          </div>
          <table style={{width:'100%', borderCollapse:'collapse'}}>
            <thead>
              <tr style={{background:'rgba(198,161,91,0.03)', borderBottom:'1px solid var(--ink-400)'}}>
                <Th>Code</Th><Th>Branch</Th><Th align="right">Screens</Th><Th align="right">Trend (12h)</Th>
              </tr>
            </thead>
            <tbody>
              {state.branches.map((b, i) => (
                <tr key={b.id} style={{borderBottom: i < state.branches.length - 1 ? '1px solid var(--ink-400)' : 'none'}}>
                  <Td><span className="cos-mono" style={{color:'var(--gold-300)'}}>{b.code}</span></Td>
                  <Td><span style={{color:'var(--ink-900)', fontWeight: 500}}>{b.name}</span></Td>
                  <Td align="right" mono>{b.screens}</Td>
                  <Td align="right"><Sparkline data={state.bookingsSpark} width={92} height={24} stroke="#6f7585"/></Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="cos-card" style={{padding: 0, position:'relative', overflow:'hidden'}}>
          <div style={{padding:'20px 24px', borderBottom:'1px solid var(--ink-400)'}}>
            <SectionLabel>Network</SectionLabel>
            <h2 style={{fontFamily:'var(--font-display)', fontSize: 18, fontWeight: 600, margin:'6px 0 0', color:'var(--ink-999)'}}>
              Iraq · Operational footprint
            </h2>
          </div>
          <div style={{padding: 16, display:'flex', justifyContent:'center'}}>
            <IraqMap width={420} height={460} branches={state.branches.map(b => ({cityCode: b.code, active: b.active, label: b.name, intensity: Math.min(1, b.screens / 6)}))}/>
          </div>
        </div>
      </div>

      {/* Today's schedule */}
      <section>
        <SectionLabel style={{marginBottom: 12, display:'block'}}>Today's schedule</SectionLabel>
        {upcoming.length === 0 ? (
          <div className="cos-card" style={{textAlign:'center', padding: 40}}>
            <p style={{margin: 0, color:'var(--text-fog-strong)', fontSize: 14}}>
              No upcoming shows today. <a href="#scheduler" style={{color:'var(--accent-gold)'}}>Open the matrix →</a>
            </p>
          </div>
        ) : (
          <div className="cos-card" style={{padding: 0, overflow:'hidden'}}>
            <table style={{width:'100%', borderCollapse:'collapse'}}>
              <thead>
                <tr style={{background:'rgba(198,161,91,0.03)', borderBottom:'1px solid var(--ink-400)'}}>
                  <Th>Movie</Th><Th>Branch</Th><Th>Hall</Th><Th>Starts at</Th><Th>Status</Th><Th align="right">Price (IQD)</Th>
                </tr>
              </thead>
              <tbody>
                {upcoming.map((s, i) => {
                  const m = movieById[s.movieId];
                  const b = branchById[s.branchId];
                  return (
                    <tr key={s.id} style={{borderBottom: i < upcoming.length - 1 ? '1px solid var(--ink-400)' : 'none'}}>
                      <Td><span style={{color:'var(--ink-999)', fontWeight: 500}}>{m?.titleEn ?? '—'}</span></Td>
                      <Td><span className="cos-mono" style={{color:'var(--gold-300)'}}>{b?.code ?? '—'}</span></Td>
                      <Td><span style={{color:'var(--ink-800)'}}>{s.hall}</span></Td>
                      <Td mono><span style={{color:'var(--ink-900)'}}>{fmtTime(s.start)}</span></Td>
                      <Td><StatusTag status={s.status}/></Td>
                      <Td align="right" mono><span style={{color:'var(--accent-gold)'}}>{s.priceIqd.toLocaleString()}</span></Td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  );
}

function FactRow({ label, value, spark, dot, valueColor, href }) {
  const row = (
    <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'14px 0', gap: 12}}>
      <MonoLabel>{label}</MonoLabel>
      <span style={{display:'inline-flex', alignItems:'center', gap: 10}}>
        {spark && <Sparkline data={spark} width={64} height={18} stroke="#6f7585"/>}
        {dot && <span style={{width: 7, height: 7, borderRadius:'50%', background: dot}}/>}
        <span className="cco-fact-value" style={{fontFamily:'var(--font-mono)', fontSize: 17, color: valueColor || 'var(--ink-999)', fontVariantNumeric:'tabular-nums', transition:'color .18s'}}>
          {value}
        </span>
      </span>
    </div>
  );
  if (href) return <a href={href} className="cco-fact-link" style={{display:'block'}}>{row}</a>;
  return row;
}

function Th({ children, align = 'left' }) {
  return <th className="cos-mono" style={{padding:'12px 20px', textAlign: align, color:'rgba(198,161,91,0.6)', fontWeight: 500}}>{children}</th>;
}
function Td({ children, align = 'left', mono }) {
  return <td style={{padding:'12px 20px', textAlign: align, color:'var(--ink-800)', fontFamily: mono ? 'var(--font-mono)' : 'inherit', fontSize: mono ? 13 : 14}}>{children}</td>;
}
function fmtTime(h) {
  const hh = Math.floor(h), mm = Math.round((h - hh) * 60);
  return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
}

window.PageOverview = PageOverview;
window.AdminUtil = { fmtTime };
