/* global React */
/* Cosidata Portal — shared primitives + sample data.
   Loaded first; exposes components on window for client.jsx / admin.jsx. */
const { useState, useEffect, useRef } = React;

const MARK = "assets/cosidata-mark.svg";
function useLucide(){ useEffect(() => { if (window.lucide) window.lucide.createIcons(); }); }
const Icon = ({ name, style, cls }) => <i data-lucide={name} className={"lucide" + (cls ? " " + cls : "")} style={style}></i>;

function Wordmark({ size = 22, dark = false }){
  return (
    <span className="wordmark" style={{ fontSize: size, display: "inline-flex", alignItems: "center", gap: 9 }}>
      <img src={MARK} alt="" style={{ height: size }} />
      <span>
        <span className="c" style={{ color: dark ? "#EEEDFE" : "var(--navy)" }}>cosi</span><span className="d">data</span>
      </span>
    </span>
  );
}

function Avatar({ name, bg = "linear-gradient(135deg,var(--primary),var(--accent))", size = 38 }){
  const initials = name.split(" ").map(w => w[0]).slice(0,2).join("").toUpperCase();
  return <div className="avatar" style={{ background: bg, width: size, height: size, fontSize: size * .36 }}>{initials}</div>;
}

function Badge({ kind = "primary", children }){
  return <span className={"badge badge-" + kind}><span className="dotb"></span>{children}</span>;
}

// ============================ SIDEBAR ============================
function Sidebar({ nav, view, onNav, user, accentLabel, open, onClose, footer }){
  useLucide();
  return (
    <aside className={"sidebar" + (open ? " open" : "")}>
      <div style={{ padding: "6px 8px 20px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <Wordmark size={22} dark />
        <button className="menu-btn" style={{ display: "none" }}></button>
      </div>
      <nav style={{ display: "grid", gap: 3, overflowY: "auto", flex: 1, marginRight: -6, paddingRight: 6 }}>
        {nav.map(item => item.group
          ? <div key={item.group} className="side-group">{item.group}</div>
          : (
            <button key={item.id} className={"side-link" + (view === item.id ? " active" : "")}
              onClick={() => onNav(item.id)}>
              <Icon name={item.icon} />
              <span style={{ flex: 1 }}>{item.label}</span>
              {item.badge && <span style={{ fontSize: 11, fontWeight: 700, color: "var(--navy)", background: "var(--lav)", borderRadius: 999, padding: "1px 8px" }}>{item.badge}</span>}
              {item.dot && <span style={{ width: 7, height: 7, borderRadius: "50%", background: item.dot }}></span>}
            </button>
          ))}
      </nav>
      <div style={{ marginTop: "auto", paddingTop: 12 }}>
        {footer}
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 8px 4px", borderTop: "1px solid rgba(255,255,255,.08)", marginTop: 10 }}>
          <Avatar name={user.name} size={34} bg={user.avatarBg} />
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: "#fff", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{user.name}</div>
            <div style={{ fontSize: 11.5, color: "rgba(238,237,254,.55)" }}>{accentLabel}</div>
          </div>
          <button onClick={user.onLogout} title="Sair" style={{ background: "transparent", border: "none", color: "rgba(238,237,254,.6)", cursor: "pointer", padding: 6, borderRadius: 8 }}
            onMouseEnter={e => e.currentTarget.style.color = "#fff"} onMouseLeave={e => e.currentTarget.style.color = "rgba(238,237,254,.6)"}>
            <Icon name="log-out" style={{ fontSize: 18 }} />
          </button>
        </div>
      </div>
    </aside>
  );
}

// ============================ TOPBAR ============================
function Topbar({ title, sub, onMenu, actions, crumb }){
  useLucide();
  return (
    <div className="topbar">
      <div style={{ display: "flex", alignItems: "center", gap: 14, minWidth: 0 }}>
        <button className="menu-btn" onClick={onMenu}><Icon name="menu" style={{ fontSize: 21 }} /></button>
        <img src="assets/cosidata-mark.svg" alt="cosidata" style={{ height: 22, width: "auto", opacity: .55, flexShrink: 0 }} className="desk" />
        <div style={{ minWidth: 0 }}>
          {crumb && <div style={{ fontSize: 12, fontWeight: 700, color: "var(--primary)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 3 }}>{crumb}</div>}
          <h1 style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{title}</h1>
          {sub && <div className="sub desk">{sub}</div>}
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>{actions}</div>
    </div>
  );
}

// ============================ KPI ============================
function KpiTile({ label, value, delta, dir = "up", icon }){
  return (
    <div className="panel kpi">
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div className="l">{label}</div>
        {icon && <Icon name={icon} style={{ fontSize: 17, color: "var(--muted)" }} />}
      </div>
      <div className="v">{value}</div>
      {delta && <span className={"delta " + dir}>{dir === "up" ? "▲" : "▼"} {delta}</span>}
    </div>
  );
}

// ============================ BAR CHART (forked) ============================
function BarChart({ title, sub, data, unit = "" }){
  const max = Math.max(...data.map(d => d[1])) * 1.12;
  return (
    <div className="panel section-card">
      <div style={{ marginBottom: 16 }}>
        <h3 style={{ fontSize: 16, fontWeight: 700 }}>{title}</h3>
        {sub && <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 3 }}>{sub}</div>}
      </div>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 9, height: 170, paddingTop: 8 }}>
        {data.map(([m, v], i) => (
          <div key={m} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8, height: "100%", justifyContent: "flex-end" }}>
            <div title={unit + v} style={{ width: "100%", maxWidth: 34, height: (v / max * 100) + "%", borderRadius: "7px 7px 3px 3px",
              background: i === data.length - 1 ? "linear-gradient(180deg,var(--accent),var(--accent-d))" : "linear-gradient(180deg,var(--primary),#5F53CA)",
              transition: "height .4s var(--ease)" }}></div>
            <span style={{ fontSize: 11, color: "var(--muted)", fontWeight: 500 }}>{m}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================ KANBAN ============================
const KAN_COLS = [
  { id: "todo", label: "A fazer", color: "var(--muted)" },
  { id: "doing", label: "Em andamento", color: "var(--amber)" },
  { id: "done", label: "Concluído", color: "var(--green)" },
];
function Kanban({ tasks, setTasks, readOnly }){
  useLucide();
  const [dragId, setDragId] = useState(null);
  const [overCol, setOverCol] = useState(null);
  const [adding, setAdding] = useState(false);
  const [draft, setDraft] = useState("");

  const move = (id, col) => setTasks(ts => ts.map(t => t.id === id ? { ...t, col } : t));
  const addTask = () => {
    const txt = draft.trim();
    if (!txt) { setAdding(false); return; }
    setTasks(ts => [...ts, { id: "t" + Date.now(), title: txt, col: "todo", tag: null }]);
    setDraft(""); setAdding(false);
  };

  return (
    <div className="kanban">
      {KAN_COLS.map(col => {
        const items = tasks.filter(t => t.col === col.id);
        return (
          <div key={col.id}
            className={"kan-col" + (overCol === col.id ? " drop-on" : "")}
            onDragOver={e => { if (readOnly) return; e.preventDefault(); setOverCol(col.id); }}
            onDragLeave={() => setOverCol(o => o === col.id ? null : o)}
            onDrop={e => { e.preventDefault(); if (dragId) move(dragId, col.id); setDragId(null); setOverCol(null); }}>
            <div className="kan-col-head">
              <span className="t"><span className="kan-dot" style={{ background: col.color }}></span>{col.label}</span>
              <span className="ct">{items.length}</span>
            </div>
            {items.map(t => (
              <div key={t.id} className={"kan-card" + (dragId === t.id ? " dragging" : "")}
                draggable={!readOnly}
                onDragStart={() => setDragId(t.id)} onDragEnd={() => { setDragId(null); setOverCol(null); }}>
                <div className="kt">{t.title}</div>
                {t.tag && <div className="km"><span className={"tag " + (t.tag.k === "p" ? "tag-p" : t.tag.k === "a" ? "tag-a" : "")}>{t.tag.label}</span></div>}
              </div>
            ))}
            {col.id === "todo" && !readOnly && (
              adding ? (
                <div className="kan-card" style={{ cursor: "default" }}>
                  <textarea autoFocus className="input" value={draft} placeholder="Nova tarefa…" rows={2}
                    onChange={e => setDraft(e.target.value)}
                    onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); addTask(); } if (e.key === "Escape") setAdding(false); }}
                    style={{ fontSize: 13.5, padding: "8px 10px", minHeight: 44 }} />
                  <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
                    <button className="btn btn-primary btn-sm" onClick={addTask}>Adicionar</button>
                    <button className="btn btn-ghost btn-sm" onClick={() => { setAdding(false); setDraft(""); }}>Cancelar</button>
                  </div>
                </div>
              ) : (
                <button onClick={() => setAdding(true)} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "10px 12px", background: "transparent", border: "1px dashed var(--line)", borderRadius: 11, color: "var(--muted)", fontSize: 13, fontWeight: 600, cursor: "pointer" }}>
                  <Icon name="plus" style={{ fontSize: 15 }} /> Adicionar tarefa
                </button>
              )
            )}
          </div>
        );
      })}
    </div>
  );
}

// ============================ COMMENTS ============================
function Comments({ thread, setThread, me }){
  useLucide();
  const [draft, setDraft] = useState("");
  const endRef = useRef(null);
  const send = () => {
    const txt = draft.trim();
    if (!txt) return;
    setThread(t => [...t, { id: "c" + Date.now(), who: me.who, name: me.name, avatarBg: me.avatarBg, time: "agora", text: txt }]);
    setDraft("");
  };
  return (
    <div>
      <div className="comments" style={{ marginBottom: 16 }}>
        {thread.length === 0 && <div style={{ fontSize: 13.5, color: "var(--muted)", padding: "8px 2px" }}>Nenhuma mensagem ainda. Comece a conversa abaixo.</div>}
        {thread.map(c => {
          const mine = c.who === me.who;
          return (
            <div key={c.id} className={"cmt" + (mine ? " me" : "")}>
              <Avatar name={c.name} size={34} bg={c.avatarBg} />
              <div className="bub">
                <div className="ch"><span className="cn">{c.name}</span><span className="ct">· {c.time}</span></div>
                <div className="cx">{c.text}</div>
              </div>
            </div>
          );
        })}
        <div ref={endRef}></div>
      </div>
      <div style={{ display: "flex", gap: 10, alignItems: "flex-end" }}>
        <textarea className="input" value={draft} placeholder="Escreva uma mensagem para o cliente…" rows={1}
          onChange={e => setDraft(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
          style={{ minHeight: 46 }} />
        <button className="btn btn-accent" onClick={send} style={{ height: 46, flexShrink: 0 }}><Icon name="send-horizontal" style={{ fontSize: 16 }} /> Enviar</button>
      </div>
    </div>
  );
}

Object.assign(window, { MARK, useLucide, Icon, Wordmark, Avatar, Badge, Sidebar, Topbar, KpiTile, BarChart, Kanban, KAN_COLS, Comments });
