// Overview tab — landing page for a single client.
// Editorial hero, hours ring, next actions, recent requests, health, upcoming.

function OverviewTab({ pal, go }) {
  const t = useTweaks();
  const jm = window.JOY_MOVE;
  const plan = jm.plans[t.tier];
  const filler = t.demo !== 'clean';

  const used = filler ? Math.min(jm.cycle.hoursUsed, plan.hoursIncluded) : 0;
  const openRequests = filler ? jm.requests.filter(r => r.status !== 'Done') : [];
  const recentRequests = filler ? jm.requests.slice(0, 4) : [];
  const awaiting = openRequests.filter(r => r.status === 'Awaiting you');
  const firstName = (jm.brand.contact || '').split(/\s+/)[0] || 'there';
  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 5) return 'Good evening';
    if (h < 12) return 'Good morning';
    if (h < 17) return 'Good afternoon';
    return 'Good evening';
  })();
  const today = new Date();
  const dayLabel = today.toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' });

  return (
    <Page pal={pal}
      kicker={dayLabel}
      title={<>{greeting}, <em style={{ fontStyle: 'italic', color: pal.accent }}>{firstName}</em></>}
      sub={filler
        ? `Here's where ${jm.brand.name} stands this cycle — ${plan.tier} plan, ${jm.cycle.periodLabel}.`
        : `Welcome to your portal. Nothing in flight yet — file your first request whenever you're ready.`}
      actions={<>
        <BtnGhost pal={pal} onClick={() => go.to('messages')}>Messages{filler ? ' · 1' : ''}</BtnGhost>
        <BtnPrimary pal={pal} onClick={go.newRequest}>+ New request</BtnPrimary>
      </>}
    >
      {/* Top row: hours ring + next actions */}
      <div style={{ display: 'grid', gridTemplateColumns: '380px 1fr', gap: 20, marginBottom: 20 }}>
        <HoursCard pal={pal} used={used} plan={plan} jm={jm} filler={filler} />
        <NextActionsCard pal={pal} awaiting={awaiting} filler={filler} go={go} />
      </div>

      {/* Middle row: recent requests + site health */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 20, marginBottom: 20 }}>
        <RecentRequestsCard pal={pal} requests={recentRequests} filler={filler} go={go} />
        <SiteHealthCard pal={pal} health={jm.siteHealth} />
      </div>

      {/* Bottom row: upcoming + plan summary */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 20 }}>
        <UpcomingCard pal={pal} items={jm.roadmap} tier={plan.tier} />
        <PlanSummaryCard pal={pal} plan={plan} jm={jm} />
      </div>
    </Page>
  );
}

function HoursCard({ pal, used, plan, jm, filler }) {
  return (
    <Card pal={pal} padding={28}>
      <Kicker pal={pal}>Cycle · {jm.cycle.periodLabel}</Kicker>
      <div style={{ display: 'flex', gap: 22, alignItems: 'center' }}>
        <HoursRing pal={pal} used={used} total={plan.hoursIncluded} size={164} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, color: pal.muted, marginBottom: 6 }}>{plan.tier} plan includes</div>
          <div style={{ fontFamily: "'Playfair Display', serif", fontSize: 26, fontWeight: 700, color: pal.navy, letterSpacing: '-0.02em' }}>
            {plan.hoursIncluded} hours <span style={{ color: pal.muted, fontSize: 13, fontWeight: 400, fontFamily: 'inherit', fontStyle: 'italic' }}>/ month</span>
          </div>
          <div style={{ fontSize: 12, color: pal.muted, marginTop: 10, lineHeight: 1.6 }}>
            <div><strong style={{ color: pal.textStrong, fontWeight: 600 }}>{used.toFixed(2)} used</strong> · {(plan.hoursIncluded - used).toFixed(2)} left</div>
            <div>Renews {jm.cycle.renews}</div>
            <div>Overage: <strong style={{ color: pal.textStrong }}>${plan.overage}/hr</strong></div>
          </div>
        </div>
      </div>
    </Card>
  );
}

function NextActionsCard({ pal, awaiting, filler, go }) {
  const rgb = hexToRgb(pal.accent);
  if (!filler) {
    return (
      <Card pal={pal} padding={0} style={{ display: 'grid', placeItems: 'center' }}>
        <EmptyState pal={pal} icon="✎"
          title="Nothing waiting on you"
          body="When we need a review or extra info, it'll show up here so nothing slips through."
          action="File your first request"
          onAction={go.newRequest}
        />
      </Card>
    );
  }
  return (
    <Card pal={pal} padding={28}>
      <Kicker pal={pal} color={pal.warn}>Waiting on you</Kicker>
      {awaiting.length === 0 ? (
        <div style={{ paddingTop: 8 }}>
          <Display pal={pal} size={24}>All clear.</Display>
          <div style={{ color: pal.muted, fontSize: 13, marginTop: 8 }}>Nothing needs your input right now.</div>
        </div>
      ) : (
        <div>
          {awaiting.map(r => (
            <div key={r.id} onClick={() => go.request(r.id)} style={{
              padding: '14px 16px', marginBottom: 10,
              background: `rgba(231,181,107,0.08)`, borderLeft: `2px solid ${pal.warn}`,
              borderRadius: 8, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              <div>
                <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: pal.muted, marginBottom: 4 }}>{r.id}</div>
                <div style={{ fontSize: 14, color: pal.textStrong, fontWeight: 500 }}>{r.title}</div>
                <div style={{ fontSize: 12, color: pal.muted, marginTop: 4, fontStyle: 'italic' }}>
                  {r.id === 'JM-213' ? 'Jordan asked for the iOS version' : 'Needs your input'}
                </div>
              </div>
              <span style={{ fontSize: 18, color: pal.warn }}>→</span>
            </div>
          ))}
          <BtnText pal={pal} onClick={() => go.to('requests')}>See all requests →</BtnText>
        </div>
      )}
    </Card>
  );
}

function RecentRequestsCard({ pal, requests, filler, go }) {
  return (
    <Card pal={pal}>
      <CardHead pal={pal} label="Recent requests" action={filler ? 'All requests' : null} onAction={() => go.to('requests')} />
      <div style={{ borderTop: `1px solid ${pal.border}` }} />
      {!filler || requests.length === 0 ? (
        <EmptyState pal={pal} icon="⊞"
          title="No requests yet"
          body={filler ? 'Nothing in flight.' : `Your first request is one click away. We'll estimate hours and confirm before starting anything over 2 hours.`}
          action="+ New request"
          onAction={go.newRequest}
        />
      ) : (
        <div>
          {requests.map((r, i) => (
            <div key={r.id} onClick={() => go.request(r.id)} style={{
              padding: '18px 24px', cursor: 'pointer',
              borderTop: i === 0 ? 'none' : `1px solid ${pal.border}`,
              display: 'flex', alignItems: 'center', gap: 16,
            }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                  <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: pal.muted }}>{r.id}</span>
                  <StatusChip pal={pal} s={r.status} />
                </div>
                <div style={{ fontSize: 14, color: pal.textStrong, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.title}</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{ fontSize: 11, color: pal.muted }}>{r.updated}</div>
                <div style={{ fontSize: 12, color: pal.textStrong, fontWeight: 500, fontFamily: "'JetBrains Mono', monospace" }}>{r.est.toFixed(2)}h</div>
              </div>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}

function SiteHealthCard({ pal, health }) {
  return (
    <Card pal={pal}>
      <CardHead pal={pal} label="Site health" />
      <div style={{ borderTop: `1px solid ${pal.border}` }} />
      <div style={{ padding: 24 }}>
        <HealthDot pal={pal} status="good" label={`All systems nominal · ${health.lastScan}`} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginTop: 22 }}>
          <KV pal={pal} label="Uptime 30d" v={`${health.uptime30}%`} mono />
          <KV pal={pal} label="Page speed" v={`${health.pageSpeed} / 100`} mono />
          <KV pal={pal} label="SSL" v={`Valid · exp ${health.ssl.expires}`} />
          <KV pal={pal} label="Last backup" v={health.lastBackup} />
          <KV pal={pal} label="Platform" v={health.platform} />
          <KV pal={pal} label="Core vitals" v={health.coreVitals} />
        </div>
      </div>
    </Card>
  );
}

function UpcomingCard({ pal, items, tier }) {
  const filtered = items.filter(x => !x.tierMin || x.tierMin === tier || tier === 'Stewardship');
  return (
    <Card pal={pal}>
      <CardHead pal={pal} label="Upcoming" />
      <div style={{ borderTop: `1px solid ${pal.border}` }} />
      <div style={{ padding: '8px 0' }}>
        {filtered.map((r, i) => (
          <div key={i} style={{
            padding: '14px 24px', display: 'flex', alignItems: 'center', gap: 16,
            borderTop: i === 0 ? 'none' : `1px solid ${pal.border}`,
          }}>
            <div style={{
              width: 58, fontFamily: "'Playfair Display', serif", fontSize: 18,
              fontWeight: 700, color: pal.accent, fontStyle: 'italic',
            }}>{r.when}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, color: pal.textStrong, fontWeight: 500 }}>{r.title}</div>
              <div style={{ fontSize: 11, color: pal.muted, letterSpacing: '0.06em', textTransform: 'uppercase', marginTop: 2 }}>{r.kind}</div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function PlanSummaryCard({ pal, plan, jm }) {
  return (
    <Card pal={pal}>
      <CardHead pal={pal} label="Your plan" />
      <div style={{ borderTop: `1px solid ${pal.border}` }} />
      <div style={{ padding: 24 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 16 }}>
          <Display pal={pal} size={26}>{plan.tier}</Display>
          <TierBadge pal={pal} tier={plan.tier} />
        </div>
        <div style={{ fontSize: 13, color: pal.muted, marginBottom: 18, lineHeight: 1.6 }}>
          ${plan.monthly}/mo · {plan.hoursIncluded} hrs included · {plan.responseSLA}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <PlanFeature pal={pal} on={plan.features.dns} label="DNS & domain support" />
          <PlanFeature pal={pal} on={plan.features.healthCheck} label="Monthly health checks" />
          <PlanFeature pal={pal} on={!!plan.features.strategy} label="Quarterly strategy call" />
          <PlanFeature pal={pal} on={!!plan.features.rollover} label={`${plan.rollover} hr rollover`} />
        </div>
        <div style={{ marginTop: 20, paddingTop: 18, borderTop: `1px solid ${pal.border}`, fontSize: 12, color: pal.muted, lineHeight: 1.6 }}>
          Client since {jm.brand.since}
        </div>
      </div>
    </Card>
  );
}

function PlanFeature({ pal, on, label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: on ? pal.textStrong : pal.dim }}>
      <span style={{ color: on ? pal.accent : pal.dim, fontSize: 12, width: 14 }}>{on ? '✓' : '—'}</span>
      <span style={{ textDecoration: on ? 'none' : 'line-through', fontWeight: on ? 500 : 400 }}>{label}</span>
    </div>
  );
}

window.OverviewTab = OverviewTab;
