/* global React, Icon */
// ============================================================
// Composants communs
// ============================================================
const { useState, useRef, useEffect, useCallback } = React;

const STATUS_META = {
  online:  { label: "En ligne",   color: "var(--online)" },
  busy:    { label: "Occupé",     color: "var(--busy)" },
  locked:  { label: "Verrouillé", color: "var(--locked)" },
  offline: { label: "Hors-ligne", color: "var(--offline)" },
};

function StatusDot({ status, pulse }) {
  const c = STATUS_META[status]?.color || "var(--faint)";
  return (
    <span style={{ position: "relative", display: "inline-flex", width: 8, height: 8 }}>
      <span style={{ width: 8, height: 8, borderRadius: 99, background: c, boxShadow: `0 0 0 3px ${c}22` }} />
      {pulse && status === "online" && (
        <span style={{ position: "absolute", inset: 0, borderRadius: 99, background: c, animation: "ping 1.6s ease-out infinite" }} />
      )}
    </span>
  );
}

function Badge({ children, tone = "neutral", soft = true, style }) {
  const tones = {
    neutral: ["var(--muted)", "var(--surface-3)"],
    green:   ["var(--accent)", "var(--accent-soft)"],
    cyan:    ["var(--accent-2)", "var(--cyan-soft)"],
    amber:   ["var(--busy)", "rgba(245,185,66,.14)"],
    red:     ["var(--danger)", "rgba(255,92,108,.14)"],
    gray:    ["var(--locked)", "rgba(139,148,167,.14)"],
  };
  const [fg, bg] = tones[tone] || tones.neutral;
  return (
    <span className="mono" style={{
      display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, fontWeight: 600,
      letterSpacing: ".02em", padding: "3px 9px", borderRadius: 99,
      color: fg, background: soft ? bg : "transparent",
      border: soft ? "none" : `1px solid ${fg}55`, whiteSpace: "nowrap", ...style,
    }}>{children}</span>
  );
}

function Avatar({ user, size = 34 }) {
  return (
    <span style={{
      width: size, height: size, borderRadius: 99, flex: "none",
      display: "grid", placeItems: "center", fontSize: size * 0.38, fontWeight: 700,
      color: "#0a0d14", background: user.avatar, fontFamily: "var(--mono)",
    }}>{user.initials}</span>
  );
}

function Button({ children, variant = "default", size = "md", icon, onClick, style, disabled, full, type = "button" }) {
  const sizes = { sm: ["6px 11px", 12.5], md: ["9px 15px", 13.5], lg: ["12px 20px", 15] };
  const [pad, fs] = sizes[size];
  const base = {
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
    padding: pad, fontSize: fs, fontWeight: 600, borderRadius: "var(--r-sm)",
    border: "1px solid transparent", transition: "all .14s ease", width: full ? "100%" : undefined,
    opacity: disabled ? 0.5 : 1, pointerEvents: disabled ? "none" : "auto", lineHeight: 1.1,
  };
  const variants = {
    default: { background: "var(--surface-3)", color: "var(--text)", border: "1px solid var(--border-2)" },
    primary: { background: "var(--accent)", color: "#06281c", fontWeight: 700, boxShadow: "0 6px 18px rgba(0,224,138,.22)", border: "1px solid transparent" },
    ghost:   { background: "transparent", color: "var(--muted)", border: "1px solid transparent" },
    outline: { background: "transparent", color: "var(--text)", border: "1px solid var(--border-2)" },
    danger:  { background: "rgba(255,92,108,.12)", color: "var(--danger)", border: "1px solid rgba(255,92,108,.3)" },
  };
  return (
    <button type={type} onClick={onClick} disabled={disabled}
      style={{ ...base, ...variants[variant], ...style }}
      onMouseEnter={(e) => { if (!disabled) e.currentTarget.style.filter = "brightness(1.12)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.filter = "none"; }}>
      {icon && React.createElement(Icon[icon], { size: fs + 3 })}
      {children}
    </button>
  );
}

function Card({ children, style, pad = 18, hover, onClick }) {
  return (
    <div onClick={onClick} style={{
      background: "var(--surface)", border: "1px solid var(--border)",
      borderRadius: "var(--r-lg)", padding: pad, boxShadow: "var(--shadow)",
      transition: "border-color .16s, transform .16s", cursor: onClick ? "pointer" : "default", ...style,
    }}
      onMouseEnter={hover ? (e) => { e.currentTarget.style.borderColor = "var(--border-2)"; e.currentTarget.style.transform = "translateY(-2px)"; } : undefined}
      onMouseLeave={hover ? (e) => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.transform = "none"; } : undefined}>
      {children}
    </div>
  );
}

// ---- iOS écran simulé (screenshot-stream) ----
const IOS_APPS = [
  ["#E1306C","IG"],["#1B88FF","S"],["#25D366","W"],["#0A84FF","A"],
  ["#34C759","✆"],["#FF9500","⚙"],["#5856D6","♫"],["#FF2D55","♥"],
  ["#FFCC00","✉"],["#30B0C7","⌘"],["#8E8E93","◷"],["#AF52DE","◐"],
];
function IOSScreen({ device, big, onTap }) {
  const ref = useRef(null);
  const [tap, setTap] = useState(null);
  const handle = (e) => {
    if (!onTap || device.status === "locked" || device.status === "offline") return;
    const r = ref.current.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width, y = (e.clientY - r.top) / r.height;
    setTap({ x, y, id: Date.now() });
    onTap({ x: +x.toFixed(3), y: +y.toFixed(3) });
    setTimeout(() => setTap(null), 520);
  };
  const locked = device.status === "locked", offline = device.status === "offline";
  return (
    <div ref={ref} onClick={handle} style={{
      position: "absolute", inset: 0, overflow: "hidden", cursor: onTap && !locked && !offline ? "crosshair" : "default",
      background: "linear-gradient(165deg, #1b2a4a 0%, #14213d 40%, #221a3a 100%)",
      animation: !locked && !offline ? "streamPulse 3s ease-in-out infinite" : "none",
    }}>
      {/* status bar */}
      {!offline && (
        <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: big ? 44 : "13%", display: "flex",
          alignItems: "center", justifyContent: "space-between", padding: big ? "0 20px" : "0 9%", color: "#fff",
          fontFamily: "var(--mono)", fontSize: big ? 14 : "5.5cqw", fontWeight: 700, zIndex: 3 }}>
          <span>{big ? "9:41" : ""}</span>
          <span style={{ opacity: .9, fontSize: big ? 12 : "4.5cqw" }}>{big ? device.battery + "%" : ""}</span>
        </div>
      )}
      {!locked && !offline && (
        <div style={{ position: "absolute", inset: big ? "48px 18px 70px" : "13% 8% 24%", display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)", gap: big ? "18px 22px" : "8% 7%", alignContent: big ? "start" : "space-evenly", zIndex: 2 }}>
          {IOS_APPS.map(([c, g], i) => (
            <div key={i} style={{ display: "grid", placeItems: "center", gap: 5 }}>
              <div style={{ aspectRatio: "1", width: "100%", borderRadius: big ? 13 : "22%", background: c,
                display: "grid", placeItems: "center", color: "#fff", fontSize: big ? 18 : "7cqw",
                fontWeight: 700, boxShadow: "0 4px 10px rgba(0,0,0,.3)" }}>{g}</div>
            </div>
          ))}
        </div>
      )}
      {/* dock */}
      {!locked && !offline && (
        <div style={{ position: "absolute", left: big ? 14 : "6%", right: big ? 14 : "6%", bottom: big ? 14 : "5%", height: big ? 78 : "13%", borderRadius: big ? 26 : "16%",
          background: "rgba(255,255,255,.12)", backdropFilter: "blur(20px)", display: "flex",
          justifyContent: "space-around", alignItems: "center", padding: big ? "0 14px" : "0 4%", zIndex: 2 }}>
          {IOS_APPS.slice(0, 4).map(([c, g], i) => (
            <div key={i} style={{ width: big ? 52 : "19%", aspectRatio: "1", borderRadius: big ? 13 : "24%", background: c, display: "grid",
              placeItems: "center", color: "#fff", fontWeight: 700, fontSize: big ? undefined : "6cqw" }}>{g}</div>
          ))}
        </div>
      )}
      {/* tap ripple */}
      {tap && (
        <span style={{ position: "absolute", left: `${tap.x * 100}%`, top: `${tap.y * 100}%`,
          width: 44, height: 44, marginLeft: -22, marginTop: -22, borderRadius: 99,
          border: "2px solid var(--accent)", background: "var(--accent-soft)",
          animation: "tapRing .52s ease-out forwards", zIndex: 5, pointerEvents: "none" }} />
      )}
      {/* locked overlay */}
      {locked && (
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", gap: 10,
          background: "rgba(8,11,18,.55)", backdropFilter: "blur(3px)", zIndex: 4, color: "#fff", textAlign: "center", padding: 18 }}>
          <div style={{ display: "grid", gap: big ? 12 : 6, justifyItems: "center" }}>
            {React.createElement(Icon.lock, { size: big ? 40 : 22 })}
            {big && <div style={{ fontSize: 15, fontWeight: 600 }}>iPhone verrouillé</div>}
            {big && <div style={{ fontSize: 12.5, color: "#cdd6e6", maxWidth: 220 }}>Déverrouillage manuel requis sur le device.</div>}
          </div>
        </div>
      )}
      {offline && (
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", gap: 8,
          background: "repeating-linear-gradient(135deg,#0c0f17,#0c0f17 10px,#0e121c 10px,#0e121c 20px)",
          zIndex: 4, color: "var(--faint)", textAlign: "center", padding: 14 }}>
          {React.createElement(Icon.phone, { size: big ? 34 : 20 })}
          {big && <div style={{ fontSize: 14, fontWeight: 600, color: "var(--muted)" }}>Hors-ligne · HC BOX coupé</div>}
        </div>
      )}
    </div>
  );
}

// ---- mini graphes SVG ----
function BarChart({ data, keys, colors, h = 180, max }) {
  const m = (max || Math.max(0, ...data.flatMap(d => keys.map(k => +d[k] || 0))) * 1.15) || 1;
  const bw = 100 / data.length;
  return (
    <svg viewBox={`0 0 ${data.length * 28} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: h }}>
      {[0.25, 0.5, 0.75, 1].map((g, i) => (
        <line key={i} x1="0" x2={data.length * 28} y1={h - g * (h - 16)} y2={h - g * (h - 16)} stroke="var(--border)" strokeWidth="1" />
      ))}
      {data.map((d, i) => {
        const x = i * 28 + 14, total = keys.length;
        return keys.map((k, j) => {
          const bh = (d[k] / m) * (h - 16);
          const w = total > 1 ? 7 : 12;
          const off = total > 1 ? (j - (total - 1) / 2) * (w + 1.5) : 0;
          return <rect key={k} x={x + off - w / 2} y={h - bh} width={w} height={bh} rx="2" fill={colors[j]} opacity={j === 0 ? 1 : 0.55} />;
        });
      })}
    </svg>
  );
}

function LineChart({ data, dkey, color = "var(--accent)", h = 180, fill = true }) {
  const max = (Math.max(0, ...data.map(d => +d[dkey] || 0)) * 1.1) || 1, min = 0;
  const W = 100;
  const pts = data.map((d, i) => [(i / (data.length - 1)) * W, h - 12 - ((d[dkey] - min) / (max - min)) * (h - 24)]);
  const path = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(2) + " " + p[1].toFixed(2)).join(" ");
  const area = path + ` L ${W} ${h} L 0 ${h} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: h }}>
      <defs>
        <linearGradient id="lg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.28" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0.33, 0.66, 1].map((g, i) => <line key={i} x1="0" x2={W} y1={h - 12 - g * (h - 24)} y2={h - 12 - g * (h - 24)} stroke="var(--border)" strokeWidth="0.5" />)}
      {fill && <path d={area} fill="url(#lg)" />}
      <path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
    </svg>
  );
}

function ProgressBar({ value, total, tone = "green", h = 6 }) {
  const pct = total ? Math.round((value / total) * 100) : 0;
  const c = { green: "var(--accent)", amber: "var(--busy)", red: "var(--danger)", cyan: "var(--accent-2)" }[tone];
  return (
    <div style={{ background: "var(--surface-3)", borderRadius: 99, height: h, overflow: "hidden" }}>
      <div style={{ width: pct + "%", height: "100%", background: c, borderRadius: 99, transition: "width .4s ease" }} />
    </div>
  );
}

function Modal({ title, children, onClose, width = 480, footer }) {
  useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(5,7,12,.66)",
      backdropFilter: "blur(4px)", display: "grid", placeItems: "center", padding: 24, animation: "appfade .18s ease" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: width, background: "var(--surface)",
        border: "1px solid var(--border-2)", borderRadius: "var(--r-xl)", boxShadow: "var(--shadow-lg)", overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 22px", borderBottom: "1px solid var(--border)" }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{title}</h3>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "var(--muted)", padding: 4, display: "grid" }}>{React.createElement(Icon.x, { size: 20 })}</button>
        </div>
        <div style={{ padding: 22, maxHeight: "64vh", overflow: "auto" }}>{children}</div>
        {footer && <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", padding: "16px 22px", borderTop: "1px solid var(--border)", background: "var(--surface-2)" }}>{footer}</div>}
      </div>
    </div>
  );
}

function SectionTitle({ children, sub }) {
  return (
    <div style={{ marginBottom: 4 }}>
      <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: "-.01em" }}>{children}</h1>
      {sub && <p style={{ margin: "5px 0 0", color: "var(--muted)", fontSize: 13.5 }}>{sub}</p>}
    </div>
  );
}

// ---- Bouton WhatsApp (ouvre wa.me) ----
function WhatsAppBtn({ user, label, variant = "pill" }) {
  if (!user || !user.whatsapp) return <span style={{ color: "var(--faint)", fontSize: 12.5 }}>—</span>;
  const num = user.whatsapp.replace(/[^\d]/g, "");
  const msg = encodeURIComponent(`Bonjour ${user.name.split(" ")[0]}, c'est l'agence Tampro 👋`);
  const icon = variant === "icon";
  return (
    <a href={`https://wa.me/${num}?text=${msg}`} target="_blank" rel="noreferrer"
      title={`WhatsApp · ${user.whatsapp}`} onClick={(e) => e.stopPropagation()}
      style={{
        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7,
        width: icon ? 32 : undefined, height: icon ? 32 : undefined,
        padding: icon ? 0 : "6px 11px", borderRadius: icon ? 9 : 8,
        background: "rgba(37,211,102,.13)", color: "#25D366", border: "1px solid rgba(37,211,102,.32)",
        fontSize: 12.5, fontWeight: 600, textDecoration: "none", whiteSpace: "nowrap", transition: "filter .14s",
      }}
      onMouseEnter={(e) => e.currentTarget.style.filter = "brightness(1.15)"}
      onMouseLeave={(e) => e.currentTarget.style.filter = "none"}>
      {React.createElement(Icon.whatsapp, { size: 16 })}{label && <span>{label}</span>}
    </a>
  );
}

// ---- Bouton Telegram (ouvre t.me/username) ----
function TelegramBtn({ user, label, variant = "icon" }) {
  if (!user || !user.telegram) return <span style={{ color: "var(--faint)", fontSize: 12.5 }}>—</span>;
  const handle = user.telegram.replace(/^@/, "");
  const icon = variant === "icon";
  return (
    <a href={`https://t.me/${handle}`} target="_blank" rel="noreferrer"
      title={`Telegram · ${user.telegram}`} onClick={(e) => e.stopPropagation()}
      style={{
        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7,
        width: icon ? 32 : undefined, height: icon ? 32 : undefined,
        padding: icon ? 0 : "6px 11px", borderRadius: icon ? 9 : 8,
        background: "rgba(42,171,238,.13)", color: "#2AABEE", border: "1px solid rgba(42,171,238,.32)",
        fontSize: 12.5, fontWeight: 600, textDecoration: "none", whiteSpace: "nowrap", transition: "filter .14s",
      }}
      onMouseEnter={(e) => e.currentTarget.style.filter = "brightness(1.15)"}
      onMouseLeave={(e) => e.currentTarget.style.filter = "none"}>
      {React.createElement(Icon.telegram, { size: 16 })}{label && <span>{label}</span>}
    </a>
  );
}

// ============================================================
// État "backend non synchronisé" — remplace les faux téléphones.
//  - variant "admin"    : explication + bouton Synchroniser.
//  - variant "operator" : bouton "Envoyer un message au manager" + contact manager.
// online=false -> pas de backend. ready=false -> 1ère connexion en cours.
// ============================================================
function SyncNotice({ online, ready, variant = "admin", onSync }) {
  const { useState } = React;
  const [busy, setBusy] = useState(false);
  const sync = async () => { setBusy(true); try { onSync && await onSync(); } finally { setBusy(false); } };

  if (!ready) {
    return (
      <div style={{ textAlign: "center", padding: "70px 20px", color: "var(--faint)" }}>
        <div style={{ width: 34, height: 34, margin: "0 auto 14px", border: "3px solid var(--border-2)", borderTopColor: "var(--accent)", borderRadius: "50%", animation: "spin 1s linear infinite" }} />
        <div style={{ fontSize: 13 }}>Connexion au parc…</div>
      </div>
    );
  }

  const manager = window.DATA ? DATA.opById("u2") : null;
  const isOp = variant === "operator";
  return (
    <div style={{ maxWidth: 520, margin: "40px auto", textAlign: "center", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", padding: "34px 28px" }}>
      <div style={{ width: 56, height: 56, margin: "0 auto 16px", borderRadius: 16, background: "var(--amber-soft, rgba(245,185,66,.12))", border: "1px solid var(--amber-line, rgba(245,185,66,.3))", display: "grid", placeItems: "center", color: "var(--amber, #f5b942)" }}>
        {React.createElement(Icon.phone, { size: 26 })}
      </div>
      <h2 style={{ margin: "0 0 8px", fontSize: 18, fontWeight: 700 }}>{isOp ? (window.t ? t("park_not_synced") : "Parc non synchronisé") : "Parc non synchronisé"}</h2>
      <p style={{ margin: "0 0 20px", color: "var(--muted)", fontSize: 13.5, lineHeight: 1.55 }}>
        {isOp
          ? (window.t ? t("op_offline") : "Les iPhones ne sont pas connectés pour le moment. Préviens ton manager pour qu'il relance la synchronisation du parc.")
          : "Aucune connexion au backend pour le moment. Relance la synchronisation, ou réessaie dans un instant."}
      </p>

      {isOp ? (
        <div>
          <div style={{ display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap" }}>
            <Button variant="outline" icon="refresh" onClick={sync} disabled={busy}>{busy ? "…" : (window.t ? t("refresh") : "Réessayer")}</Button>
            <Button variant="primary" icon="send" onClick={() => { if (window.ChatUI) ChatUI.set(true); }}>{window.t ? t("send_msg_manager") : "Envoyer un message au manager"}</Button>
          </div>
          {manager && (
            <div style={{ marginTop: 20, display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 12, textAlign: "left" }}>
              <Avatar user={manager} size={38} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{manager.name}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--faint)" }}>Manager · {manager.email}</div>
              </div>
              <WhatsAppBtn user={manager} variant="icon" />
              <TelegramBtn user={manager} variant="icon" />
            </div>
          )}
        </div>
      ) : (
        <div>
          <Button variant="primary" icon="refresh" onClick={sync} disabled={busy}>{busy ? "Synchronisation…" : "Synchroniser le backend"}</Button>
          <div className="mono" style={{ marginTop: 14, fontSize: 11, color: "var(--faint)" }}>
            {online ? "Backend joignable mais aucun iPhone détecté — branche/déverrouille un iPhone." : "Backend injoignable — réessaie dans un instant."}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { STATUS_META, StatusDot, Badge, Avatar, Button, Card, IOSScreen, BarChart, LineChart, ProgressBar, Modal, SectionTitle, WhatsAppBtn, TelegramBtn, SyncNotice });
