// Shared components: Shell (header/nav/footer), RadialRadar, Badge, Chip.
// Referenced by public.jsx, admin.jsx.

const S = window.OSS_STYLE;

// ─── Shell ─────────────────────────────────────────────────────
function Shell({ route, setRoute, children, extraNav, variant }) {
  const isAdmin = variant === 'admin';
  const sections = isAdmin
    ? [
        { id: 'panoramica', label: 'Panoramica' },
        { id: 'redazione', label: 'Redazione' },
        { id: 'agenti', label: 'Agenti' },
        { id: 'registro', label: 'Registro' },
        { id: 'audit', label: 'Audit' },
      ]
    : [
        { id: 'home', label: 'Osservatorio' },
        { id: 'analisi', label: 'Analisi' },
        { id: 'radar', label: 'Radar' },
        // Database e Dashboard sono nascosti dal menu: i contenuti attuali
        // sono dati dimostrativi del prototipo. Le sezioni torneranno
        // quando un agente Statistico curerà dati reali.
        // { id: 'database', label: 'Database' },
        // { id: 'dashboard', label: 'Dashboard' },
        { id: 'about', label: 'Manifesto' },
      ];
  const state = window.OssStore.load();
  return (
    <div style={{ background: S.bg, color: S.ink, minHeight: '100vh', fontFamily: S.sans }}>
      <header style={{ padding: '24px 64px 22px', display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 40, borderBottom: `1px solid ${S.rule}` }}>
        <div style={{ fontFamily: S.mono, fontSize: 11, letterSpacing: 2, textTransform: 'uppercase', color: S.muted }}>
          <span style={{ color: S.accent2, marginRight: 10 }}>●</span>
          {isAdmin
            ? 'Console redazionale'
            : (state.brand.issue && state.brand.date)
              ? `${state.brand.issue} · ${state.brand.date}`
              : 'In formazione · 2026'}
        </div>
        <a href={isAdmin ? './index.html' : './index.html'} onClick={(e) => { e.preventDefault(); setRoute({ name: isAdmin ? 'panoramica' : 'home' }); }} style={{ textDecoration: 'none', color: 'inherit', textAlign: 'center' }}>
          <div style={{ fontFamily: S.display, fontSize: 26, fontWeight: 400, letterSpacing: -0.4, lineHeight: 1 }}>
            Osservatorio <span style={{ fontStyle: 'italic' }}>CDTI</span>
          </div>
          <div style={{ fontFamily: S.mono, fontSize: 9, letterSpacing: 3, textTransform: 'uppercase', color: S.muted, marginTop: 4 }}>sulla intelligenza artificiale</div>
        </a>
        <div style={{ textAlign: 'right', fontFamily: S.mono, fontSize: 11, letterSpacing: 1, color: S.muted, textTransform: 'uppercase' }}>
          {isAdmin ? (
            <a href="./index.html" style={{ color: S.accent, textDecoration: 'none' }}>← Sito pubblico</a>
          ) : (
            <a href="./admin.html" style={{ color: S.muted, textDecoration: 'none' }}>Redazione ↗</a>
          )}
        </div>
      </header>
      <nav style={{ display: 'flex', justifyContent: 'center', gap: 42, padding: '16px 0', borderBottom: `1px solid ${S.rule}`, fontFamily: S.sans, fontSize: 13, letterSpacing: 0.5 }}>
        {sections.map((s) => (
          <button key={s.id} onClick={() => setRoute({ name: s.id })}
            style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'inherit', padding: 0,
              color: route.name === s.id ? S.accent2 : S.ink,
              borderBottom: route.name === s.id ? `1.5px solid ${S.accent2}` : '1.5px solid transparent',
              paddingBottom: 4, fontWeight: route.name === s.id ? 500 : 400 }}>
            {s.label}
          </button>
        ))}
        {extraNav}
      </nav>
      {children}
      <footer style={{ padding: '40px 64px', borderTop: `1px solid ${S.rule}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 24, flexWrap: 'wrap', fontFamily: S.mono, fontSize: 11, color: S.muted, letterSpacing: 1, textTransform: 'uppercase' }}>
        <span>© 2026 Osservatorio CDTI</span>
        {!isAdmin && (
          <a href="#/carta" onClick={(e) => { e.preventDefault(); setRoute({ name: 'carta' }); }}
            style={{ color: S.muted, textDecoration: 'none', borderBottom: `1px dotted ${S.dim}`, paddingBottom: 2 }}>
            Carta costitutiva
          </a>
        )}
        <span style={{ fontFamily: S.display, fontStyle: 'italic', textTransform: 'none', fontSize: 15, letterSpacing: 0, color: S.ink }}>{state.brand.tagline}</span>
        <span>v1.0 · {isAdmin ? 'console' : 'pubblico'}</span>
      </footer>
    </div>
  );
}

// ─── RadialRadar (adapted from direction C) ───────────────────
function RadialRadar({ items, onHover, onSelect, size = 480 }) {
  const R = size / 2;
  const regions = ['EU', 'IT', 'US', 'APAC'];
  const regionAngle = Object.fromEntries(regions.map((r, i) => [r, (i / regions.length) * Math.PI * 2 - Math.PI / 2]));
  const positioned = items.slice(0, 24).map((n, i) => {
    const baseAngle = regionAngle[n.region] ?? 0;
    const spread = ((i * 37) % 60 - 30) * (Math.PI / 180);
    const angle = baseAngle + spread * 0.4;
    const priorityR = n.priority === 'high' ? 0.55 : n.priority === 'med' ? 0.75 : 0.92;
    const r = priorityR * (R - 30) + ((i * 13) % 30);
    return { ...n, x: R + Math.cos(angle) * r, y: R + Math.sin(angle) * r, r };
  });
  return (
    <div style={{ position: 'relative', width: size, height: size, margin: '0 auto' }}>
      <svg width={size} height={size} style={{ position: 'absolute', inset: 0 }}>
        {[0.25, 0.5, 0.75, 1].map((f) => (
          <circle key={f} cx={R} cy={R} r={(R - 20) * f} fill="none" stroke={S.rule} strokeWidth="0.5" strokeDasharray={f === 1 ? 'none' : '2 4'} />
        ))}
        {regions.map((r) => {
          const a = regionAngle[r];
          const x2 = R + Math.cos(a) * (R - 20), y2 = R + Math.sin(a) * (R - 20);
          const lx = R + Math.cos(a) * (R - 5), ly = R + Math.sin(a) * (R - 5);
          return (
            <g key={r}>
              <line x1={R} y1={R} x2={x2} y2={y2} stroke={S.rule} strokeWidth="0.5" />
              <text x={lx} y={ly} fontFamily={S.mono} fontSize="10" fill={S.muted} textAnchor="middle" dominantBaseline="middle" letterSpacing="2">{r}</text>
            </g>
          );
        })}
        <circle cx={R} cy={R} r={(R - 20) * 0.25} fill="none" stroke={S.accent2} strokeWidth="0.6" strokeDasharray="2 3" />
        <text x={R} y={R - 4} fontFamily={S.mono} fontSize="9" fill={S.accent2} textAnchor="middle" letterSpacing="2">ALTA PRIORITÀ</text>
        <circle cx={R} cy={R} r="3" fill={S.accent2} />
        {positioned.map((p) => (
          <g key={p.id} style={{ cursor: 'pointer' }}
            onClick={() => onSelect && onSelect(p)}
            onMouseEnter={() => onHover && onHover(p)}
            onMouseLeave={() => onHover && onHover(null)}>
            <circle cx={p.x} cy={p.y} r={p.priority === 'high' ? 5 : p.priority === 'med' ? 3.5 : 2.5}
              fill={p.priority === 'high' ? S.accent2 : S.accent} opacity="0.85" />
            <circle cx={p.x} cy={p.y} r={p.priority === 'high' ? 12 : 6}
              fill={p.priority === 'high' ? S.accent2 : S.accent} opacity="0.1" />
          </g>
        ))}
      </svg>
    </div>
  );
}

// ─── Micro-UI primitives ──────────────────────────────────────
function Chip({ children, color, dim }) {
  const bg = dim ? 'transparent' : (color || S.ink);
  const fg = dim ? (color || S.muted) : S.bg;
  const bd = dim ? `1px solid ${color || S.rule}` : 'none';
  return (
    <span style={{ display: 'inline-block', padding: '2px 10px', background: bg, color: fg, border: bd,
      fontFamily: S.mono, fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase' }}>
      {children}
    </span>
  );
}

function StatusChip({ status }) {
  const map = {
    draft: { label: 'Bozza', color: S.warn, dim: true },
    published: { label: 'Pubblicato', color: S.success, dim: false },
    archived: { label: 'Archiviato', color: S.muted, dim: true },
    pending: { label: 'In arrivo', color: S.accent, dim: true },
    review: { label: 'In revisione', color: S.warn, dim: false },
    approved: { label: 'Approvato', color: S.success, dim: false },
    rejected: { label: 'Rifiutato', color: S.accent2, dim: true },
  };
  const m = map[status] || { label: status, color: S.muted, dim: true };
  return <Chip color={m.color} dim={m.dim}>{m.label}</Chip>;
}

function Button({ children, onClick, variant, tiny, disabled, style }) {
  const base = {
    padding: tiny ? '4px 10px' : '8px 16px', border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
    fontFamily: S.sans, fontSize: tiny ? 11 : 13, letterSpacing: 0.3,
    background: 'transparent', color: S.ink, opacity: disabled ? 0.45 : 1,
  };
  const variants = {
    primary: { background: S.ink, color: S.bg },
    accent: { background: S.accent2, color: '#fff' },
    ghost: { background: 'transparent', color: S.accent, border: `1px solid ${S.rule}` },
    quiet: { background: 'transparent', color: S.muted },
    danger: { background: 'transparent', color: S.accent2, border: `1px solid ${S.accent2}` },
  };
  return (
    <button onClick={disabled ? undefined : onClick} disabled={disabled}
      style={{ ...base, ...(variants[variant] || variants.ghost), ...style }}>
      {children}
    </button>
  );
}

function Field({ label, children, hint }) {
  return (
    <label style={{ display: 'block', marginBottom: 20 }}>
      <div style={{ fontFamily: S.mono, fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', color: S.muted, marginBottom: 6 }}>{label}</div>
      {children}
      {hint && <div style={{ fontFamily: S.serif, fontSize: 13, fontStyle: 'italic', color: S.muted, marginTop: 6 }}>{hint}</div>}
    </label>
  );
}

function Input(props) {
  return <input {...props} style={{
    width: '100%', padding: '10px 12px', background: '#fff',
    border: `1px solid ${S.rule}`, fontFamily: S.serif, fontSize: 15, color: S.ink, outline: 'none',
    ...(props.style || {}),
  }} />;
}
function Textarea(props) {
  return <textarea {...props} style={{
    width: '100%', padding: '12px', background: '#fff',
    border: `1px solid ${S.rule}`, fontFamily: S.serif, fontSize: 15, color: S.ink, outline: 'none',
    resize: 'vertical', minHeight: 120, lineHeight: 1.55,
    ...(props.style || {}),
  }} />;
}
function Select(props) {
  return <select {...props} style={{
    width: '100%', padding: '10px 12px', background: '#fff',
    border: `1px solid ${S.rule}`, fontFamily: S.sans, fontSize: 14, color: S.ink, outline: 'none',
    ...(props.style || {}),
  }} />;
}

window.OssComponents = { Shell, RadialRadar, Chip, StatusChip, Button, Field, Input, Textarea, Select };
