const { useState, useMemo, useEffect, useRef } = React;

function Logo({ size = 28, color = "var(--primary)" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" stroke={color} strokeWidth="2.3" strokeLinecap="round" aria-hidden="true">
      <path d="M7.63 14.52A8.5 8.5 0 0 1 24.37 14.52" />
      <path d="M24.37 17.48A8.5 8.5 0 0 1 7.63 17.48" />
      <path d="M1 16h4.6M26.4 16H31" />
      <circle cx="16" cy="16" r="3.2" fill={color} stroke="none" />
    </svg>
  );
}

function Wordmark({ sub }) {
  return (
    <div className="wm">
      <img src="assets/cyclope-logo.png" alt="Cyclope" width="30" height="30" style={{ borderRadius: 9, display: "block", flex: "0 0 auto" }} />
      <div>
        <div className="wm-name">Cyclope</div>
        {sub ? <div className="wm-sub">{sub}</div> : null}
      </div>
    </div>
  );
}

const I = {
  queue: "M3 6h18M3 12h18M3 18h11",
  check: "M20 6 9 17l-5-5",
  x: "M18 6 6 18M6 6l12 12",
  wand: "M15 4V2M15 16v-2M8 9h2M20 9h2M17.8 11.8l1.4 1.4M17.8 6.2l1.4-1.4M3 21l9-9",
  gear: "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0-1.2-2.9H1a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 2.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.9.3H7a1.7 1.7 0 0 0 1-1.5V1a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V7a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z",
  mail: "M3 6h18v12H3zM3 6l9 7 9-7",
  users: "M16 20v-1.5A3.5 3.5 0 0 0 12.5 15h-5A3.5 3.5 0 0 0 4 18.5V20M10 11.5a3.75 3.75 0 1 0 0-7.5 3.75 3.75 0 0 0 0 7.5ZM20 20v-1.5a3.5 3.5 0 0 0-2.6-3.4M15.5 4.2a3.75 3.75 0 0 1 0 7.1",
  chart: "M4 20V10M10 20V4M16 20v-7M22 20H2",
  arrow: "M5 12h14M13 6l6 6-6 6",
  back: "M19 12H5M11 6l-6 6 6 6",
  alert: "M12 4 2 20h20L12 4ZM12 10v5M12 17.5v.5",
  clock: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18ZM12 7v5l3.5 2",
  plug: "M9 3v6M15 3v6M6 9h12v3a6 6 0 0 1-12 0V9ZM12 18v3",
  eye: "M2 12s3.6-6 10-6 10 6 10 6-3.6 6-10 6-10-6-10-6Z M12 14.2a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4Z",
  copy: "M9 9h10v12H9zM5 15V3h10",
  dot: "M12 12h.01",
};

function Ic({ d, s = 16, w = 1.7, style }) {
  return <svg className="ic" width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={w} strokeLinecap="round" strokeLinejoin="round" style={style}><path d={I[d] || d} /></svg>;
}

function Btn({ children, kind = "ghost", icon, onClick, disabled, full, size }) {
  return (
    <button className={`btn b-${kind}${full ? " b-full" : ""}${size === "s" ? " b-s" : ""}`} onClick={onClick} disabled={disabled}>
      {icon ? <Ic d={icon} s={size === "s" ? 14 : 16} /> : null}{children}
    </button>
  );
}

function RiskTag({ level, small }) {
  const r = RISK[level];
  return <span className={`rt${small ? " rt-s" : ""}`} style={{ color: r.color, background: r.bg }}><span className="rt-bars">{[1, 2, 3].map(i => <i key={i} style={{ background: i <= r.n ? r.color : "currentColor", opacity: i <= r.n ? 1 : .22 }} />)}</span>{r.label}</span>;
}

function CatTag({ cat }) { return <span className="ct">{CATS[cat].short}</span>; }
function Pill({ tone = "n", children }) { return <span className={`pill p-${tone}`}>{children}</span>; }

function Card({ title, sub, right, children, pad = true }) {
  return (
    <section className="card">
      {title ? <header className="card-h"><div><h3>{title}</h3>{sub ? <p>{sub}</p> : null}</div>{right}</header> : null}
      <div className={pad ? "card-b" : ""}>{children}</div>
    </section>
  );
}

function Field({ label, hint, children, mono }) {
  return <label className={`fld${mono ? " fld-m" : ""}`}><span className="fld-l">{label}</span>{children}{hint ? <span className="fld-h">{hint}</span> : null}</label>;
}

function Toggle({ on, onChange, label }) {
  return <button className={`tg${on ? " on" : ""}`} onClick={() => onChange(!on)} aria-pressed={on} aria-label={label}><i /></button>;
}

function Seg({ value, onChange, options }) {
  return <div className="seg">{options.map(o => <button key={o.v} className={value === o.v ? "on" : ""} onClick={() => onChange(o.v)}>{o.l}{o.n != null ? <em>{o.n}</em> : null}</button>)}</div>;
}

function Stat({ k, v, d, tone }) {
  return <div className="stat"><div className="stat-k">{k}</div><div className={`stat-v tone-${tone}`}>{typeof v === "number" ? v.toLocaleString("fr-FR") : v}</div><div className="stat-d">{d}</div></div>;
}

function Bars() {
  const max = Math.max(...SERIES.map(s => s.a));
  return (
    <div className="bars">
      {SERIES.map((s, i) => (
        <div className="bar-col" key={i}>
          <div className="bar-stack" title={`${s.a.toLocaleString("fr-FR")} analysés`}>
            <div className="bar b-a" style={{ height: `${(s.a / max) * 100}%` }}><div className="bar b-c" style={{ height: `${(s.c / s.a) * 100}%` }} /></div>
          </div>
          <span>{s.d}</span>
        </div>
      ))}
    </div>
  );
}

function Empty({ icon = "check", title, sub }) {
  return <div className="empty"><div className="empty-i"><Ic d={icon} s={20} /></div><strong>{title}</strong><p>{sub}</p></div>;
}

/* ---- shell shared by the two spaces ---- */
function useTheme() {
  const [dark, setDark] = useState(() => localStorage.getItem("cyclope-theme") === "dark");
  useEffect(() => {
    document.documentElement.dataset.theme = dark ? "dark" : "light";
    localStorage.setItem("cyclope-theme", dark ? "dark" : "light");
  }, [dark]);
  return [dark, setDark];
}

function useDecisions() {
  const [decisions, setDecisions] = useState(() => { try { return JSON.parse(localStorage.getItem("cyclope-decisions") || "{}"); } catch (e) { return {}; } });
  const decide = (id, d) => setDecisions(x => { const n = { ...x, [id]: d }; localStorage.setItem("cyclope-decisions", JSON.stringify(n)); return n; });
  return [decisions, decide];
}

function Side({ space, nav, view, onView, badge, user, other }) {
  const [dark, setDark] = useTheme();
  return (
    <aside className="side">
      <Wordmark sub={space === "consultant" ? "Espace consultant" : "Espace administrateur"} />
      <div className="space-tag"><Ic d={space === "consultant" ? "eye" : "gear"} s={15} />{space === "consultant" ? "Revue des e-mails" : "Configuration"}</div>
      <nav className="nav-g">
        <div className="nav-t">Navigation</div>
        {nav.map(n => (
          <button key={n.v} className={`nav-i${view === n.v ? " on" : ""}`} onClick={() => onView(n.v)}>
            <Ic d={n.i} s={16} />{n.l}{n.badge && badge ? <b>{badge}</b> : null}
          </button>
        ))}
      </nav>
      <div className="side-f">
        {other ? <a className="xlink" href="#" onClick={e => { e.preventDefault(); other.onClick && other.onClick(); }}><Ic d={other.i} s={15} />{other.l}<Ic d="arrow" s={14} /></a> : null}
        <div className="theme">Thème sombre<Toggle on={dark} onChange={setDark} label="Thème sombre" /></div>
        <div className="org"><span className="av">{user.initials}</span><div style={{ minWidth: 0, flex: 1 }}><b>{user.name}</b><span>{user.org}</span></div>
          <button className="side-logout" onClick={() => window.CYCLOPE_AUTH && window.CYCLOPE_AUTH.logout()} title="Se déconnecter" style={{ border: 0, background: "none", color: "var(--ink-3)", cursor: "pointer", fontSize: 11, fontWeight: 600, padding: "4px 2px", whiteSpace: "nowrap" }}>Quitter</button>
        </div>
      </div>
    </aside>
  );
}

Object.assign(window, { Logo, Wordmark, Ic, I, Btn, RiskTag, CatTag, Pill, Card, Field, Toggle, Seg, Stat, Bars, Empty, Side, useTheme, useDecisions });
