// Klyvio — Shared UI pieces (dark theme Klyvio)

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

/* ———————————————————— LOGO ———————————————————— */
function Logo({ size = 22 }) {
  const h = Math.round(size * 2);
  return (
    <img
      src={(typeof window !== "undefined" && window.__resources && window.__resources.logo) || "assets/klyvio-logo.png"}
      alt="Klyvio"
      style={{ height: h, width: "auto", display: "block", alignSelf: "flex-start" }}
    />
  );
}

/* ———————————————————— PAGE CHROME ———————————————————— */
function AppChrome({ current, onNav, children, hideNav = false }) {
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 960;

  const items = [
    { id: "landing",    label: "Accueil",          icon: "home" },
    { id: "onboarding", label: "Démarrer l\'audit", icon: "sparkles" },
    { id: "audit",      label: "Questionnaire",    icon: "compass" },
    { id: "loading",    label: "Analyse",          icon: "bolt" },
    { id: "report",     label: "Rapport",          icon: "fileText" },
  ];

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      {!hideNav && (
        <header style={{
          display: "flex",
          alignItems: "center",
          padding: "12px 28px",
          borderBottom: "1px solid var(--border)",
          background: "rgba(8, 15, 26, 0.88)",
          backdropFilter: "blur(16px)",
          WebkitBackdropFilter: "blur(16px)",
          position: "sticky",
          top: 0,
          zIndex: 50,
        }}>
          <button
            onClick={() => onNav("landing")}
            style={{ background: "none", border: "none", cursor: "pointer", padding: 0 }}
          >
            <Logo size={44} />
          </button>

          <nav className="app-nav" style={{ display: isMobile ? "none" : "flex", gap: 2, marginLeft: 28 }}>
            {items.map((it, idx) => {
              const isActive = current === it.id;
              return (
                <button
                  key={it.id}
                  aria-label={it.label}
                  className={"nav-item" + (idx >= 4 ? " nav-secondary" : "")}
                  onClick={() => onNav(it.id)}
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 6,
                    padding: "7px 12px",
                    fontSize: 13,
                    fontWeight: 500,
                    border: "none",
                    background: isActive ? "var(--accent)" : "transparent",
                    color: isActive ? "#000" : "var(--gray)",
                    borderRadius: 999,
                    cursor: "pointer",
                    transition: "all .2s ease",
                  }}
                  onMouseEnter={e => {
                    if (!isActive) {
                      e.currentTarget.style.background = "var(--accent-dim)";
                      e.currentTarget.style.color = "var(--accent)";
                    }
                  }}
                  onMouseLeave={e => {
                    if (!isActive) {
                      e.currentTarget.style.background = "transparent";
                      e.currentTarget.style.color = "var(--gray)";
                    }
                  }}
                >
                  <Icon name={it.icon} size={13} />
                  <span className="nav-label">{it.label}</span>
                </button>
              );
            })}
          </nav>

          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10 }}>
            {!isMobile && (
              <span className="chip" style={{ fontSize: 11, color: "var(--text-mute)" }}>
                Beta
              </span>
            )}
            <button
              className="btn btn-ghost btn-sm"
              onClick={() => onNav("login")}
              style={{ fontSize: 12 }}
            >
              <Icon name="grid" size={13} /> Se connecter
            </button>
          </div>
        </header>
      )}

      <main style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        {children}
      </main>
    </div>
  );
}

/* ———————————————————— CIRCULAR SCORE ———————————————————— */
function ScoreDial({ value = 0, size = 220, stroke = 14, label = "Maturité IA", sub }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const offset = c - (value / 100) * c;

  const bandColor = value < 30 ? "var(--danger-500)"
                  : value < 55 ? "var(--warn-500)"
                  : value < 75 ? "var(--accent)"
                  : "var(--success-500)";

  const gradId = `dial-grad-${size}-${Math.round(value)}`;

  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size}>
        <defs>
          <linearGradient id={gradId} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor={bandColor} />
            <stop offset="100%" stopColor="var(--accent)" />
          </linearGradient>
        </defs>
        <circle cx={size / 2} cy={size / 2} r={r} stroke="var(--gray-dim)" strokeWidth={stroke} fill="none" />
        <circle
          cx={size / 2} cy={size / 2} r={r}
          stroke={`url(#${gradId})`} strokeWidth={stroke} fill="none"
          strokeDasharray={c} strokeDashoffset={offset}
          strokeLinecap="round"
          transform={`rotate(-90 ${size / 2} ${size / 2})`}
          style={{ transition: "stroke-dashoffset 1.2s cubic-bezier(.2,.8,.2,1)" }}
        />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <div style={{ fontSize: size * 0.26, fontFamily: "var(--font-sans)", fontWeight: 800, lineHeight: 1, color: "var(--white)", fontVariantNumeric: "tabular-nums" }}>
          {Math.round(value)}
        </div>
        <div style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 600, color: "var(--text-mute)", marginTop: 6 }}>
          {label}
        </div>
        {sub && <div style={{ fontSize: 12, color: "var(--gray)", marginTop: 2 }}>{sub}</div>}
      </div>
    </div>
  );
}

/* ———————————————————— RADAR ———————————————————— */
function RadarChart({ data, size = 320, max = 100 }) {
  const cx = size / 2;
  const cy = size / 2;
  const r  = size / 2 - 44;
  const n  = data.length;
  const angle = (i) => (Math.PI * 2 * i) / n - Math.PI / 2;

  const point = (i, v) => {
    const a  = angle(i);
    const rr = (v / max) * r;
    return [cx + Math.cos(a) * rr, cy + Math.sin(a) * rr];
  };

  const polyPoints = data.map((d, i) => point(i, d.value).join(",")).join(" ");
  const gridLevels = [0.25, 0.5, 0.75, 1];

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ overflow: "visible" }}>
      {gridLevels.map((lvl, k) => (
        <polygon key={k}
          points={data.map((_, i) => { const a = angle(i); return [cx + Math.cos(a) * r * lvl, cy + Math.sin(a) * r * lvl].join(","); }).join(" ")}
          fill="none" stroke="rgba(0,174,239,0.15)"
          strokeWidth={k === gridLevels.length - 1 ? 1.2 : 0.8}
          strokeDasharray={k === gridLevels.length - 1 ? "" : "3 3"}
        />
      ))}
      {data.map((_, i) => {
        const [x, y] = point(i, max);
        return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="rgba(0,174,239,0.12)" strokeWidth="0.8" />;
      })}
      <polygon points={polyPoints} fill="rgba(0,174,239,0.10)" stroke="var(--accent)" strokeWidth="1.8" style={{ transition: "all .6s ease" }} />
      {data.map((d, i) => {
        const [x, y] = point(i, d.value);
        return <g key={i}><circle cx={x} cy={y} r="4" fill="var(--bg2)" stroke="var(--accent)" strokeWidth="2" /></g>;
      })}
      {data.map((d, i) => {
        const a      = angle(i);
        const lx     = cx + Math.cos(a) * (r + 26);
        const ly     = cy + Math.sin(a) * (r + 26);
        const anchor = Math.abs(Math.cos(a)) < 0.3 ? "middle" : Math.cos(a) > 0 ? "start" : "end";
        return (
          <g key={`lbl-${i}`}>
            <text x={lx} y={ly} textAnchor={anchor} dominantBaseline="middle" style={{ fontSize: 12, fontWeight: 600, fill: "var(--white)", fontFamily: "Outfit, sans-serif" }}>{d.label}</text>
            <text x={lx} y={ly + 15} textAnchor={anchor} dominantBaseline="middle" style={{ fontSize: 10, fill: "var(--gray)", fontFamily: "Outfit, sans-serif" }}>{Math.round(d.value)}/100</text>
          </g>
        );
      })}
    </svg>
  );
}

/* ———————————————————— STAT CARD ———————————————————— */
function StatCard({ eyebrow, value, unit, sub, icon, tone = "default", trend, className = "" }) {
  const tones = {
    default: { bg: "var(--bg2)",        accent: "var(--accent)", text: "var(--white)" },
    accent:  { bg: "linear-gradient(135deg, rgba(0,174,239,0.2), rgba(0,136,204,0.15))", accent: "var(--accent)", text: "var(--white)" },
    dark:    { bg: "var(--bg)",         accent: "var(--accent)", text: "var(--white)" },
    soft:    { bg: "var(--accent-dim)", accent: "var(--accent)", text: "var(--white)" },
  };
  const t = tones[tone] || tones.default;

  return (
    <div className={`card ${className}`} style={{ background: t.bg, color: t.text, padding: "22px 24px", display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <div className="eyebrow" style={{ color: "var(--text-mute)" }}>{eyebrow}</div>
        {icon && (
          <div style={{ width: 28, height: 28, borderRadius: 8, background: "var(--accent-dim)", border: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--accent)" }}>
            <Icon name={icon} size={14} />
          </div>
        )}
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
        <div style={{ fontSize: 48, fontFamily: "var(--font-sans)", fontWeight: 800, letterSpacing: "-0.025em", color: t.text, fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>{value}</div>
        {unit && <div style={{ fontSize: 16, color: "var(--gray)" }}>{unit}</div>}
      </div>
      {(sub || trend) && (
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--gray)" }}>
          {trend && (
            <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: trend > 0 ? "var(--success-500)" : "var(--danger-500)" }}>
              <Icon name={trend > 0 ? "trendUp" : "trendDown"} size={12} />
              {trend > 0 ? "+" : ""}{trend}%
            </span>
          )}
          {sub}
        </div>
      )}
    </div>
  );
}

/* ———————————————————— UTILS ———————————————————— */
function formatEur(n) {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n > 10_000_000 ? 0 : 1)}\u202fM€`;
  if (n >= 1_000)     return `${Math.round(n / 100) / 10}\u202fk€`;
  return `${Math.round(n)}\u202f€`;
}

function formatHours(n) {
  if (n >= 1000) return `${Math.round(n / 100) / 10}\u202fk\u202fh`;
  return `${Math.round(n)}\u202fh`;
}

Object.assign(window, { Logo, AppChrome, ScoreDial, RadarChart, StatCard, formatEur, formatHours });
