// ════════════════════════════════════════════════════════════════
// ICONS — light stroke, geometric, lucide-style
// ════════════════════════════════════════════════════════════════

const Icon = ({ name, size = 16, stroke = 1.5 }) => {
  const props = {
    width: size,
    height: size,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: stroke,
    strokeLinecap: "round",
    strokeLinejoin: "round",
  };
  const paths = {
    dashboard: <><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></>,
    building: <><path d="M3 21h18"/><path d="M5 21V7l8-4v18"/><path d="M19 21V11l-6-4"/><path d="M9 9h.01M9 12h.01M9 15h.01M9 18h.01"/></>,
    link: <><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></>,
    activity: <><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></>,
    user: <><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></>,
    plus: <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
    check: <><polyline points="20 6 9 17 4 12"/></>,
    checkbig: <><polyline points="20 6 9 17 4 12"/></>,
    x: <><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></>,
    arrowRight: <><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></>,
    copy: <><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></>,
    refresh: <><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10"/><path d="M20.49 15a9 9 0 0 1-14.85 3.36L1 14"/></>,
    eye: <><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></>,
    eyeOff: <><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></>,
    search: <><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></>,
    chevronRight: <><polyline points="9 18 15 12 9 6"/></>,
    chevronDown: <><polyline points="6 9 12 15 18 9"/></>,
    moreHorizontal: <><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></>,
    moreVertical: <><circle cx="12" cy="12" r="1"/><circle cx="12" cy="5" r="1"/><circle cx="12" cy="19" r="1"/></>,
    download: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></>,
    external: <><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></>,
    lock: <><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></>,
    shield: <><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></>,
    zap: <><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></>,
    clock: <><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></>,
    alert: <><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></>,
    info: <><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></>,
    cloud: <><path d="M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z"/></>,
    database: <><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></>,
    box: <><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></>,
    chart: <><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></>,
    arrowLeft: <><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></>,
    logout: <><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></>,
    file: <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></>,
    sparkle: <><path d="M12 2l1.5 4.5L18 8l-4.5 1.5L12 14l-1.5-4.5L6 8l4.5-1.5L12 2z"/><path d="M19 14l.75 2.25L22 17l-2.25.75L19 20l-.75-2.25L16 17l2.25-.75L19 14z"/></>,
    bell: <><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></>,
    key: <><circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/></>,
    pen: <><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/></>,
    contaazul: null,
    powerbi: null,
  };
  return <svg {...props}>{paths[name]}</svg>;
};

// Brand-ish logo marks
const ContaAzulMark = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
    <rect x="2" y="2" width="20" height="20" rx="4" fill="#0099ff"/>
    <path d="M8 12c0-2 1.5-3.5 3.5-3.5 1 0 1.8.4 2.3.9l-1.2 1.3c-.3-.3-.7-.5-1.1-.5-1 0-1.8.8-1.8 1.8s.8 1.8 1.8 1.8c.4 0 .8-.2 1.1-.5l1.2 1.3c-.5.5-1.3.9-2.3.9-2 0-3.5-1.5-3.5-3.5z" fill="#fff"/>
    <circle cx="16" cy="13.5" r="1.8" fill="#fff"/>
  </svg>
);

const PowerBIMark = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
    <rect x="2" y="2" width="20" height="20" rx="4" fill="#f2c811"/>
    <rect x="5.5" y="13" width="3" height="6" rx="0.5" fill="#000" opacity="0.85"/>
    <rect x="10.5" y="9" width="3" height="10" rx="0.5" fill="#000" opacity="0.85"/>
    <rect x="15.5" y="5" width="3" height="14" rx="0.5" fill="#000" opacity="0.85"/>
  </svg>
);

const SupabaseMark = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
    <rect x="2" y="2" width="20" height="20" rx="4" fill="#3ECF8E"/>
    <path d="M13 4 L7 13 H12 L11 20 L17 11 H12 L13 4 Z" fill="#fff"/>
  </svg>
);

const BridgeMark = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
    <path d="M4 16 V13 a8 8 0 0 1 16 0 v3" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
    <line x1="4" y1="16" x2="20" y2="16" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
    <line x1="8" y1="16" x2="8" y2="20" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
    <line x1="16" y1="16" x2="16" y2="20" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
    <line x1="12" y1="13" x2="12" y2="20" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
  </svg>
);

// ════════════════════════════════════════════════════════════════
// MARQUEE
// ════════════════════════════════════════════════════════════════

const Marquee = () => {
  const items = [
    "7 dias de garantia",
    "100% LGPD compliant",
    "Refresh token automático",
    "OAuth 2.0 da Conta Azul",
    "Endpoint estático para Power BI",
    "+500 empresas #conectados",
    "Suporte em pt-BR",
    "Vault criptografado",
  ];
  const all = [...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {all.map((t, i) => (
          <span key={i} className="marquee-item">
            <span>{t}</span>
            <span className="marquee-diamond">◆</span>
          </span>
        ))}
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// SIDEBAR
// ════════════════════════════════════════════════════════════════

const Sidebar = ({ route, setRoute, user, empresas }) => {
  const itemsTop = [
    { id: "dashboard", label: "Dashboard", icon: "dashboard" },
    { id: "empresas", label: "Empresas", icon: "building", badge: empresas.length },
    { id: "logs", label: "Logs da API", icon: "activity" },
  ];
  const itemsBottom = [
    { id: "conta", label: "Conta", icon: "user" },
    { id: "settings", label: "Configurações", icon: "settings", disabled: true },
  ];
  const isActive = (id) => {
    if (id === "dashboard") return route.name === "dashboard";
    if (id === "empresas") return ["empresas", "empresa-new", "empresa", "oauth"].includes(route.name);
    return route.name === id;
  };

  return (
    <aside className="sidebar">
      <div className="sb-brand">
        <div className="sb-brand-mark"><BridgeMark size={16}/></div>
        <div className="sb-brand-text">
          <span className="sb-brand-name">API Bridge</span>
          <span className="sb-brand-sub">Revolution</span>
        </div>
      </div>

      <span className="sb-section">Plataforma</span>
      {itemsTop.map(it => (
        <button
          key={it.id}
          className={"sb-item" + (isActive(it.id) ? " active" : "")}
          onClick={() => setRoute({ name: it.id })}
        >
          <span className="sb-item-icon"><Icon name={it.icon} size={16}/></span>
          <span>{it.label}</span>
          {it.badge != null && <span className="sb-badge">{it.badge}</span>}
        </button>
      ))}

      <span className="sb-section">Conta</span>
      {itemsBottom.map(it => (
        <button
          key={it.id}
          className={"sb-item" + (isActive(it.id) ? " active" : "")}
          onClick={() => !it.disabled && setRoute({ name: it.id })}
          style={it.disabled ? { opacity: 0.4, cursor: "not-allowed" } : {}}
        >
          <span className="sb-item-icon"><Icon name={it.icon} size={16}/></span>
          <span>{it.label}</span>
        </button>
      ))}

      <div className="sb-user">
        <div className="sb-user-avatar">{user.name.split(" ").map(n => n[0]).slice(0,2).join("")}</div>
        <div className="sb-user-info">
          <div className="sb-user-name">{user.name}</div>
          <div className="sb-user-mail">{user.email}</div>
        </div>
      </div>
    </aside>
  );
};

// ════════════════════════════════════════════════════════════════
// COPY TOAST
// ════════════════════════════════════════════════════════════════

const useCopyToast = () => {
  const [msg, setMsg] = React.useState("");
  const [show, setShow] = React.useState(false);
  const timerRef = React.useRef();

  const copy = (text, label = "URL copiada para a área de transferência") => {
    try {
      navigator.clipboard?.writeText(text);
    } catch (e) {}
    setMsg(label);
    setShow(true);
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => setShow(false), 2200);
  };

  const Toast = () => (
    <div className={"copy-toast" + (show ? " show" : "")}>
      {msg}
    </div>
  );
  return { copy, Toast };
};

// ════════════════════════════════════════════════════════════════
// FLOW MAP (you → platform → contaazul → powerbi)
// ════════════════════════════════════════════════════════════════

const FlowMap = ({ activeStep = 0 }) => {
  // 0 = none, 1 = user→bridge, 2 = bridge→contaazul, 3 = contaazul→powerbi
  const nodes = [
    { icon: <Icon name="user" size={14}/>, label: "Você" },
    { icon: <BridgeMark size={14}/>, label: "API Bridge" },
    { icon: <ContaAzulMark size={18}/>, label: "Conta Azul", brand: true },
    { icon: <PowerBIMark size={18}/>, label: "Power BI", brand: true },
  ];
  return (
    <div className="flow-map">
      <div className="flow-map-title">Fluxo da Autorização</div>
      <div className="flow-nodes">
        {nodes.map((n, i) => (
          <React.Fragment key={i}>
            <div className={"flow-node" + (activeStep >= i + 1 ? " active" : "")}>
              <div className="flow-node-icon" style={n.brand ? { border: "none", background: "transparent" } : {}}>
                {n.icon}
              </div>
              <div className="flow-node-label">{n.label}</div>
            </div>
            {i < nodes.length - 1 && (
              <div className={"flow-arrow" + (activeStep >= i + 1 ? " active" : "")}>
                <Icon name="arrowRight" size={14}/>
              </div>
            )}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// TOKEN TIMER (30min countdown ring)
// ════════════════════════════════════════════════════════════════

const TokenTimer = ({ minutesElapsed = 12, total = 30, paused = false }) => {
  const left = Math.max(0, total - minutesElapsed);
  const pct = Math.max(0, Math.min(1, left / total));
  const r = 72;
  const C = 2 * Math.PI * r;
  const dash = C * pct;
  const offset = C - dash;
  const state = left < 5 ? "danger" : left < 15 ? "warn" : "ok";
  return (
    <div className="token-timer">
      <div className="token-timer-head">
        <div className="token-timer-title">Refresh Token Timer</div>
        <span className={"badge badge-" + (state === "ok" ? "green" : state === "warn" ? "yellow" : "red")}>
          <span className="badge-dot" style={{ background: "currentColor" }}/>
          {state === "ok" ? "Token ativo" : state === "warn" ? "Renovar logo" : "Renovação iminente"}
        </span>
      </div>
      <div className="token-timer-ring-wrap">
        <div className="token-timer-ring">
          <svg viewBox="0 0 160 160">
            <circle cx="80" cy="80" r={r} fill="none" strokeWidth="10" className="token-timer-ring-bg"/>
            <circle
              cx="80" cy="80" r={r} fill="none" strokeWidth="10"
              strokeLinecap="round"
              strokeDasharray={C}
              strokeDashoffset={offset}
              className={"token-timer-ring-fill" + (state === "warn" ? " warn" : state === "danger" ? " danger" : "")}
            />
          </svg>
          <div className="token-timer-center">
            <div className="token-timer-num">{left}</div>
            <div className="token-timer-unit">min restantes</div>
          </div>
        </div>
      </div>
      <div className="token-timer-foot">
        <div className="token-timer-explain">
          O <span className="strong">access_token</span> atual é usado por até <span className="strong">30 minutos</span>.
          Após esse limite, a próxima chamada do Power BI dispara o <span className="strong">refresh_token</span> automaticamente — o usuário não percebe.
        </div>
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// STATUS BADGE
// ════════════════════════════════════════════════════════════════

const StatusBadge = ({ status }) => {
  const map = {
    connected: { cls: "badge-green", label: "Conectado", dot: true, pulse: true },
    needs_refresh: { cls: "badge-yellow", label: "Refresh pendente", dot: true },
    pending: { cls: "badge-neutral", label: "Aguardando autorização", dot: false },
    connecting: { cls: "badge-orange", label: "Conectando…", dot: true, pulse: true },
    error: { cls: "badge-red", label: "Erro de autenticação", dot: true },
  };
  const s = map[status] || map.pending;
  return (
    <span className={"badge " + s.cls}>
      {s.dot && <span className={"badge-dot" + (s.pulse ? " badge-dot-pulse" : "")} style={{ background: "currentColor" }}/>}
      {s.label}
    </span>
  );
};

// ════════════════════════════════════════════════════════════════
// PAGE HEAD
// ════════════════════════════════════════════════════════════════

const PageHead = ({ overline, title, sub, children }) => (
  <div className="page-head">
    <div className="page-head-left">
      {overline && <span className="page-overline">{overline}</span>}
      <h1 className="page-title">{title}</h1>
      {sub && <p className="page-sub">{sub}</p>}
    </div>
    {children && <div className="page-actions">{children}</div>}
  </div>
);

Object.assign(window, {
  Icon, ContaAzulMark, PowerBIMark, SupabaseMark, BridgeMark,
  Marquee, Sidebar, useCopyToast, FlowMap, TokenTimer, StatusBadge, PageHead,
});
