// Radar — the relationship intelligence screen. Novel polar viz.
// Center = you. Distance = days since meaningful exchange. Size = volume. Color = type.

function RadarScreen({ go }) {
  const d = LifeData;
  const [activeId, setActiveId] = React.useState(null);
  const active = activeId && d.people.find(p => p.id === activeId);

  const W = 370, H = 330, CX = W/2, CY = H/2 - 4;
  const rings = [
    { label: 'TODAY',     r: 38,  days: 1 },
    { label: 'THIS WEEK', r: 80,  days: 7 },
    { label: 'THIS MONTH',r: 122, days: 30 },
    { label: 'DRIFTED',   r: 158, days: 90 },
  ];
  const maxR = 158;

  const dayToR = (days) => {
    if (days < 1) return 22 + days * 16;
    if (days < 7) return 38 + ((days - 1) / 6) * 42;
    if (days < 30) return 80 + ((days - 7) / 23) * 42;
    return Math.min(122 + ((days - 30) / 60) * 36, 162);
  };

  const typeAngles = { family: -45, partner: 60, friend: 180, work: 285 };
  const indexInType = {};
  const defaultGradient = ['#8E8E93', '#636366'];
  const positioned = d.people.map((p) => {
    const pg = Array.isArray(p.gradient) && p.gradient.length >= 2 ? p.gradient : defaultGradient;
    const base = typeAngles[p.type] ?? 0;
    indexInType[p.type] = (indexInType[p.type] || 0);
    const spread = 120;
    const count = d.people.filter(x => x.type === p.type).length;
    const offset = count > 1 ? (indexInType[p.type] / (count - 1) - 0.5) * spread : 0;
    indexInType[p.type] += 1;
    const angle = (base + offset) * Math.PI / 180;
    const r = dayToR(p.days_since ?? 999);
    return { ...p, gradient: pg, x: CX + Math.cos(angle) * r, y: CY + Math.sin(angle) * r, r };
  });

  const dotSize = (msgs) => Math.max(6, Math.min(18, 5 + Math.sqrt(Number(msgs) || 0) * 0.7));

  if (d.people.length === 0) {
    return (
      <div style={{ paddingBottom: 110 }}>
        <div style={{ padding: '64px 20px 8px' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>Relationship Radar</div>
          <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.6, lineHeight: '38px', marginTop: 4 }}>Who am I orbiting?</div>
        </div>
        <div style={{ padding: '20px 16px' }}>
          <Card style={{ padding: 24, textAlign: 'center' }}>
            <IconGhost size={40} color={T.label3} />
            <div style={{ fontSize: 17, fontWeight: 600, marginTop: 12 }}>No relationship data yet</div>
            <div style={{ fontSize: 14, color: T.label2, marginTop: 6, lineHeight: '20px' }}>
              Import your WhatsApp export to see your relationship radar and drift scores.
            </div>
          </Card>
        </div>
      </div>
    );
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Header */}
      <div style={{ padding: '64px 20px 8px' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>
          Relationship Radar
        </div>
        <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.6, lineHeight: '38px', marginTop: 4 }}>
          Who am I orbiting?
        </div>
      </div>

      {/* Radar */}
      <div style={{ padding: '14px 16px 0', position: 'relative' }}>
        <Card style={{ padding: 0, overflow: 'hidden' }}>
          <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
            <defs>
              <radialGradient id="radarGlow" cx="50%" cy="50%" r="60%">
                <stop offset="0%" stopColor="#007AFF" stopOpacity="0.10" />
                <stop offset="100%" stopColor="#007AFF" stopOpacity="0" />
              </radialGradient>
              <radialGradient id="pulseGlow" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor="#FF3B30" stopOpacity="0.5" />
                <stop offset="100%" stopColor="#FF3B30" stopOpacity="0" />
              </radialGradient>
              {positioned.map(p => (
                <radialGradient key={'g'+p.id} id={'g'+p.id} cx="30%" cy="30%" r="80%">
                  <stop offset="0%" stopColor={p.gradient[0]} />
                  <stop offset="100%" stopColor={p.gradient[1]} />
                </radialGradient>
              ))}
            </defs>

            <circle cx={CX} cy={CY} r={maxR} fill="url(#radarGlow)" />

            {rings.map(ring => (
              <g key={ring.label}>
                <circle cx={CX} cy={CY} r={ring.r} fill="none" stroke="rgba(60,60,67,0.10)" strokeWidth="1" strokeDasharray="2 3" />
                <text x={CX} y={CY - ring.r - 4} textAnchor="middle" fill="rgba(60,60,67,0.32)" fontSize="9" fontWeight="600" letterSpacing="0.5">
                  {ring.label}
                </text>
              </g>
            ))}

            <line x1={CX} y1={CY - maxR} x2={CX} y2={CY + maxR} stroke="rgba(60,60,67,0.05)" />
            <line x1={CX - maxR} y1={CY} x2={CX + maxR} y2={CY} stroke="rgba(60,60,67,0.05)" />

            <text x={CX + 124} y={CY - 100} fill="rgba(60,60,67,0.4)" fontSize="9" fontWeight="600" letterSpacing="0.6">FAMILY</text>
            <text x={CX - 18} y={CY + 168} fill="rgba(60,60,67,0.4)" fontSize="9" fontWeight="600" letterSpacing="0.6">PARTNER</text>
            <text x={CX - 168} y={CY + 8} fill="rgba(60,60,67,0.4)" fontSize="9" fontWeight="600" letterSpacing="0.6">FRIENDS</text>
            <text x={CX + 100} y={CY + 8} fill="rgba(60,60,67,0.4)" fontSize="9" fontWeight="600" letterSpacing="0.6">WORK</text>

            <circle cx={CX} cy={CY} r={10} fill="#000" />
            <circle cx={CX} cy={CY} r={5} fill="#fff" />

            {positioned.filter(p => p.ghost).map(p => (
              <line key={'l'+p.id} x1={CX} y1={CY} x2={p.x} y2={p.y}
                    stroke={T.red} strokeOpacity="0.18" strokeWidth="1" strokeDasharray="2 2" />
            ))}

            {positioned.map(p => {
              const size = dotSize(p.msgs_30d ?? p.msg_count ?? 0);
              const isActive = activeId === p.id;
              return (
                <g key={p.id} onClick={() => setActiveId(p.id)} style={{ cursor: 'pointer' }}>
                  {p.ghost && (
                    <circle cx={p.x} cy={p.y} r={size + 12} fill="url(#pulseGlow)">
                      <animate attributeName="r" values={`${size + 8};${size + 18};${size + 8}`} dur="2.4s" repeatCount="indefinite" />
                      <animate attributeName="opacity" values="0.9;0.3;0.9" dur="2.4s" repeatCount="indefinite" />
                    </circle>
                  )}
                  {isActive && (
                    <circle cx={p.x} cy={p.y} r={size + 7} fill="none" stroke={p.gradient[1]} strokeWidth="1.5" />
                  )}
                  <circle cx={p.x} cy={p.y} r={size} fill={`url(#g${p.id})`} stroke="#fff" strokeWidth="2" />
                  <text x={p.x} y={p.y + size + 13} textAnchor="middle" fontSize="10.5" fontWeight="600" fill={isActive ? '#000' : 'rgba(60,60,67,0.85)'} style={{ pointerEvents: 'none' }}>
                    {p.name}
                  </text>
                </g>
              );
            })}
          </svg>

          <div style={{ padding: '8px 14px 12px', display: 'flex', gap: 14, fontSize: 11, color: T.label2 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <Dot color={T.red} /> ghosted
            </span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 14, height: 14, border: '1.5px solid #ddd', borderRadius: 999, display: 'inline-block' }} />
              size = volume
            </span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 5, marginLeft: 'auto' }}>
              {d.people.filter(p => p.days_since > 7).length} drifting
            </span>
          </div>
        </Card>
      </div>

      {/* Selected person preview */}
      {active && (
        <div style={{ padding: '14px 16px 0' }}>
          <Card onClick={() => go('person', active.id)} style={{
            background: grad(active.gradient[0], active.gradient[1]),
            color: '#fff', padding: 16, position: 'relative', overflow: 'hidden',
          }}>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.4 }}>
                  <Bi>{active.name}</Bi> <span style={{ opacity: 0.7, fontWeight: 500, fontSize: 16 }}>· {active.en !== active.name ? active.en : active.type}</span>
                </div>
                <div style={{ fontSize: 13, opacity: 0.85, marginTop: 2, textTransform: 'capitalize' }}>{active.type}</div>
              </div>
              <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.85, letterSpacing: 0.5, textTransform: 'uppercase' }}>
                {active.days_since === 0 ? 'TODAY' : `${active.days_since}D AGO`}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 18, marginTop: 12 }}>
              <Metric label="Messages" value={(active.msg_count ?? 0).toLocaleString()} dark />
              <Metric label="Last contact" value={active.days_since === 0 ? 'Today' : `${active.days_since}d ago`} dark />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14 }}>
              <span style={{ fontSize: 13, opacity: 0.9 }}>Open dossier</span>
              <IconChevR size={18} color="#fff" />
            </div>
          </Card>
        </div>
      )}

      {/* Waiting on you */}
      {d.people.filter(p => p.ghost).length > 0 && (
        <Section title="Waiting on you" style={{ marginTop: 22 }}>
          <Card padded={false}>
            {d.people.filter(p => p.ghost).map((p, i, arr) => (
              <div key={p.id} onClick={() => go('person', p.id)} style={{
                display: 'flex', alignItems: 'center', minHeight: 60, padding: '10px 14px',
                borderBottom: i < arr.length - 1 ? `0.5px solid ${T.sep}` : 'none',
                cursor: 'pointer',
              }}>
                <Avatar p={p} size={36} />
                <div style={{ flex: 1, marginLeft: 12, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 500 }}><Bi>{p.name}</Bi></div>
                  <div style={{ fontSize: 12, color: T.label2 }}>
                    {p.days_since === 0 ? 'replied recently' : `${p.days_since}d ago`}
                  </div>
                </div>
                <span style={{
                  fontSize: 11, fontWeight: 600, color: p.days_since > 10 ? T.red : T.orange,
                  padding: '4px 8px', borderRadius: 999,
                  background: p.days_since > 10 ? 'rgba(255,59,48,0.10)' : 'rgba(255,149,0,0.12)',
                }}>
                  {p.days_since > 30 ? 'COLD' : p.days_since > 10 ? 'DRIFTING' : 'OWED'}
                </span>
              </div>
            ))}
          </Card>
        </Section>
      )}

    </div>
  );
}

function fmtMin(min) {
  if (min < 60) return `${min}m`;
  if (min < 1440) return `${Math.round(min / 60)}h`;
  return `${Math.round(min / 1440)}d`;
}

function Metric({ label, value, dark }) {
  return (
    <div>
      <div style={{ fontSize: 11, opacity: dark ? 0.7 : 1, color: dark ? '#fff' : T.label2, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 19, fontWeight: 700, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    </div>
  );
}

function Avatar({ p, size = 40 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 999,
      background: grad((p.gradient || ['#8E8E93'])[0], (p.gradient || ['#8E8E93','#636366'])[1]),
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: '#fff', fontSize: size * 0.4, fontWeight: 600,
      flexShrink: 0,
    }}>
      <Bi>{(p.name || '?')[0]}</Bi>
    </div>
  );
}

// ── Person detail (full screen) ─────────────────────────────────────────────
function PersonScreen({ id, go }) {
  const d = LifeData;
  const p = d.people.find(x => x.id === id) || d.people[0];
  if (!p) return null;
  const det = (d.personDetails && d.personDetails[p.id]) || null;
  const pg = Array.isArray(p.gradient) && p.gradient.length >= 2 ? p.gradient : ['#8E8E93', '#636366'];

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Hero */}
      <div style={{
        background: grad(pg[0], pg[1]),
        padding: '64px 20px 26px',
        color: '#fff', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -40, right: -40, width: 200, height: 200, borderRadius: 999,
          background: 'rgba(255,255,255,0.08)', filter: 'blur(2px)',
        }} />
        <div onClick={() => go('radar')} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 13, fontWeight: 500, opacity: 0.85, cursor: 'pointer', marginBottom: 10 }}>
          <IconChevL size={16} color="#fff" /> Radar
        </div>
        <Avatar p={p} size={56} />
        <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: -0.5, marginTop: 12 }}>
          <Bi>{p.name}</Bi> {p.en !== p.name && <span style={{ opacity: 0.7, fontWeight: 500, fontSize: 18 }}>· {p.en}</span>}
        </div>
        <div style={{ fontSize: 14, opacity: 0.9, textTransform: 'capitalize', marginTop: 2 }}>
          {p.type}
        </div>
      </div>

      {/* Last + pattern */}
      {det && (
        <div style={{ padding: '14px 16px 0' }}>
          <Card>
            <div style={{ fontSize: 11, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>Last exchange</div>
            <div style={{ fontSize: 15, marginTop: 6, lineHeight: '21px' }}><Bi>{det.last_exchange}</Bi></div>
            <div style={{ height: 1, background: T.sep, margin: '12px 0' }} />
            <div style={{ fontSize: 11, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>Pattern</div>
            <div style={{ fontSize: 15, marginTop: 6, lineHeight: '21px' }}>{det.pattern}</div>
          </Card>
        </div>
      )}

      {/* Metrics grid — only show stats backed by real data */}
      <Section title="Relationship stats" style={{ marginTop: 22 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <StatTile label="Total messages" value={(p.msg_count ?? 0).toLocaleString()} sub="all time" />
          <StatTile label="Last contact" value={p.days_since === 0 ? 'Today' : `${p.days_since}d ago`} sub={p.last_msg || '—'} />
          {det && <StatTile label="Ghost events" value={det.ghost_events} sub="they sent, no reply" bad={det.ghost_events > 0} />}
          {det && <StatTile label="Sessions" value={det.total_sessions} sub="conversations total" />}
        </div>
      </Section>

      {/* Topics — if personDetails available */}
      {det && det.topics && det.topics.length > 0 && (
        <Section title="What you usually talk about" style={{ marginTop: 22 }}>
          <Card>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {det.topics.map(t => (
                <span key={t} style={{
                  padding: '6px 12px', borderRadius: 999, background: T.bg, fontSize: 13, fontWeight: 500,
                }}><Bi>{t}</Bi></span>
              ))}
            </div>
          </Card>
        </Section>
      )}

      {/* Action items */}
      {det && det.action_items && det.action_items.length > 0 && (
        <Section title="You promised them" style={{ marginTop: 22 }}>
          <Card padded={false}>
            {det.action_items.map((a, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px',
                borderBottom: i < det.action_items.length - 1 ? `0.5px solid ${T.sep}` : 'none',
              }}>
                <div style={{ width: 22, height: 22, borderRadius: 999, border: `1.5px solid ${T.label3}` }} />
                <span style={{ fontSize: 14, flex: 1 }}><Bi>{a}</Bi></span>
              </div>
            ))}
          </Card>
        </Section>
      )}

      {/* Action buttons */}
      <div style={{ display: 'flex', gap: 10, padding: '22px 16px 0' }}>
        <button onClick={() => go('chat')} style={_btnStyle('primary', pg[1])}>
          <IconReply size={16} color="#fff" /> <span>Message in chat</span>
        </button>
        <button onClick={() => go('radar')} style={_btnStyle('secondary')}>
          <IconRadar size={16} color={T.label} /> <span>Back to radar</span>
        </button>
      </div>
    </div>
  );
}

function StatTile({ label, value, sub, bad }) {
  return (
    <Card style={{ padding: 12 }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: T.label2, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 22, fontWeight: 700, marginTop: 4, letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums', color: bad ? T.red : T.label }}>{value}</div>
      <div style={{ fontSize: 11, color: T.label2, marginTop: 1 }}>{sub}</div>
    </Card>
  );
}

function Sparkline({ data, color }) {
  const W = 320, H = 60, pad = 4;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = pad + (i / (data.length - 1)) * (W - 2*pad);
    const y = pad + (1 - (v - min) / range) * (H - 2*pad);
    return [x, y];
  });
  const path = pts.map(([x,y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(' ');
  const area = path + ` L${pts[pts.length-1][0]},${H} L${pts[0][0]},${H} Z`;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
      <defs>
        <linearGradient id="spkGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.2" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#spkGrad)" />
      <path d={path} fill="none" stroke={color} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
      {pts.map(([x,y], i) => (
        <circle key={i} cx={x} cy={y} r={i === pts.length - 1 ? 3 : 2} fill={color} />
      ))}
    </svg>
  );
}

function _btnStyle(kind, accent = T.blue) {
  if (kind === 'primary') {
    return {
      flex: 1, height: 46, borderRadius: 14, border: 'none', cursor: 'pointer',
      background: accent, color: '#fff', fontSize: 15, fontWeight: 600,
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
    };
  }
  return {
    flex: 1, height: 46, borderRadius: 14, border: 'none', cursor: 'pointer',
    background: T.bg2, color: T.label, fontSize: 15, fontWeight: 600,
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
    boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
  };
}

Object.assign(window, { RadarScreen, PersonScreen, Avatar, Metric, fmtMin });
