/* ============================================================
   Media SOP — App shell, role switching, state & wiring
   ============================================================ */
const { useState } = React;

const AppCtx = React.createContext(null);
const useApp = () => React.useContext(AppCtx);
window.useApp = useApp;

const ROLE_TITLE = { order: "Người Order", editor: "Editor", manager: "Quản lý / Lead" };
const ROLE_COLOR = {
  order:   "linear-gradient(135deg,oklch(0.55 0.18 250),oklch(0.50 0.16 270))",
  editor:  "linear-gradient(135deg,oklch(0.55 0.20 290),oklch(0.50 0.18 310))",
  manager: "linear-gradient(135deg,oklch(0.55 0.20 290),oklch(0.50 0.18 320))",
};

const NAV = {
  order: [
    { key: "new", label: "Tạo Order", icon: "order" },
    { key: "orders", label: "Order của tôi", icon: "inbox" },
  ],
  editor: [
    { key: "myboard", label: "Việc của tôi", icon: "kanban" },
    { key: "mykpi", label: "KPI của tôi", icon: "trendUp" },
  ],
  manager: [
    { key: "dashboard", label: "Dashboard KPI", icon: "dashboard" },
    { key: "intake", label: "Tiếp nhận & Estimate", icon: "briefcase" },
    { key: "board", label: "Kanban team", icon: "kanban" },
    { key: "staff", label: "Nhân sự", icon: "users" },
  ],
};
const DEFAULT_ROUTE  = { order: "new", editor: "myboard", manager: "dashboard" };
const PAGE_META = {
  new: ["Tạo Order", "Gửi yêu cầu sản phẩm media"],
  orders: ["Order của tôi", "Theo dõi & nghiệm thu sản phẩm"],
  myboard: ["Việc của tôi", "Kéo-thả cập nhật trạng thái công việc"],
  mykpi: ["KPI của tôi", "Hiệu suất · chất lượng · deadline"],
  dashboard: ["Dashboard KPI", "Tổng hợp hiệu suất & leaderboard editor"],
  intake: ["Tiếp nhận & Estimate", "Gán editor và ước tính giờ"],
  board: ["Kanban điều phối", "Toàn bộ công việc của team"],
  staff: ["Nhân sự Media", "Quản lý level & năng lực editor"],
};

function now() {
  const d = new Date();
  return "Hôm nay " + d.toLocaleTimeString("vi-VN", { hour: "2-digit", minute: "2-digit" });
}
let _nid = 1;

function App({ supabaseUser, supabaseProfile }) {
  const role  = supabaseProfile?.role  || "order";
  const persona = {
    name:     supabaseProfile?.name  || supabaseUser?.email || "Người dùng",
    dept:     supabaseProfile?.dept  || "",
    role,
    title:    ROLE_TITLE[role],
    color:    ROLE_COLOR[role],
    editorId: supabaseProfile?.editor_id || null,
  };

  const [route, setRoute] = useState(DEFAULT_ROUTE[role]);
  const [editors, setEditors] = useState(SEED_EDITORS);
  const [orders, setOrders] = useState(SEED_ORDERS);
  const [notifs, setNotifs] = useState([
    { id: 0, from: "Media SOP Bot", icon: "trophy", text: "🏆 <b>Leaderboard tháng 5</b> đã cập nhật. Hoàng Anh Tuấn dẫn đầu KPI.", time: "Hôm nay 08:00" },
  ]);
  const [toasts, setToasts] = useState([]);
  const [tgOpen, setTgOpen] = useState(false);
  const [editorDetail, setEditorDetail] = useState(null);
  const [navOpen, setNavOpen] = useState(false);

  const editorById = (id) => editors.find(e => e.id === id);

  const go = (r) => { setRoute(r); setNavOpen(false); };

  async function handleLogout() {
    await window.supabaseClient.auth.signOut();
  }

  // ---- notifications ----
  const notify = ({ text, icon = "send", from = "Media SOP Bot" }) => {
    const n = { id: _nid++, text, icon, from, time: now() };
    setNotifs(p => [n, ...p]);
    const tid = _nid++;
    setToasts(p => [...p, { id: tid, text, icon }]);
    setTimeout(() => setToasts(p => p.filter(t => t.id !== tid)), 4200);
  };

  // ---- order actions ----
  const createOrder = (f) => {
    const o = {
      id: "ORD-" + (1043 + orders.length), title: f.title, vtype: f.vtype, purpose: f.purpose,
      deadline: f.deadline, priority: f.priority, addons: f.addons || [], requester: f.requester,
      dept: f.dept || "", stage: "intake", editorId: null, estimateHours: null, actualHours: null,
      rating: null, deadlineMet: null, finalLink: null, feedback: [], createdAt: new Date().toISOString().slice(0,10),
    };
    setOrders(p => [o, ...p]);
    notify({ icon: "order", text: `🆕 <b>Order mới</b> từ ${f.requester} (${f.dept}): “${f.title}” [${f.vtype}] · deadline ${fmtDate(f.deadline)}. Chờ tiếp nhận.` });
    return o;
  };

  const intakeOrder = (id, editorId, hours, addonPcts = {}) => {
    const ed = editorById(editorId);
    setOrders(p => p.map(o => o.id === id ? { ...o, editorId, estimateHours: hours, addonPcts, stage: "doing" } : o));
    setEditors(p => p.map(e => e.id === editorId ? { ...e, activeTasks: e.activeTasks + 1 } : e));
    const o = orders.find(x => x.id === id);
    notify({ icon: "checkCircle", text: `✅ <b>Đã tiếp nhận</b> “${o.title}” → giao ${ed.name}. Dự kiến hoàn thành: <b>${fmtDate(o.deadline)}</b>.` });
  };

  const moveOrder = (id, stage) => {
    const o = orders.find(x => x.id === id);
    if (!o || o.stage === stage) return;
    setOrders(p => p.map(x => x.id === id ? { ...x, stage } : x));
    if (stage === "review") notify({ icon: "star", text: `📦 “${o.title}” đã sẵn sàng — mời ${o.requester} <b>nghiệm thu</b>.` });
    else if (stage === "feedback") notify({ icon: "message", text: `✏️ “${o.title}” chuyển sang <b>sửa theo feedback</b>.` });
    else if (stage === "doing") notify({ icon: "video", text: `🎬 Editor bắt đầu thực hiện “${o.title}”.` });
    else if (stage === "done") notify({ icon: "checkCircle", text: `🎉 “${o.title}” đã <b>hoàn tất & lưu trữ</b>.` });
  };

  const acceptOrder = (id, rating, onTime) => {
    const o = orders.find(x => x.id === id);
    setOrders(p => p.map(x => x.id === id ? { ...x, stage: "done", rating, deadlineMet: onTime } : x));
    if (o.editorId) {
      setEditors(p => p.map(e => e.id === o.editorId ? {
        ...e, products: e.products + 1, hiStar: e.hiStar + (rating >= 4 ? 1 : 0),
        onTime: e.onTime + (onTime ? 1 : 0), activeTasks: Math.max(0, e.activeTasks - 1),
      } : e));
    }
    const ed = editorById(o.editorId);
    notify({ icon: "star", text: `⭐ ${o.requester} nghiệm thu “${o.title}”: <b>${rating}★</b> · ${onTime ? "đúng hạn" : "trễ hạn"}. KPI ${ed?.name} đã cập nhật.` });
  };

  const updateOrder = (id, patch) => setOrders(p => p.map(o => o.id === id ? { ...o, ...patch } : o));
  const addFeedback = (id, by, fbRole, text) => {
    setOrders(p => p.map(o => {
      if (o.id !== id) return o;
      const feedback = [...o.feedback, { by, role: fbRole, text, at: now() }];
      const stage = (fbRole === "order" && o.stage === "review") ? "feedback" : o.stage;
      return { ...o, feedback, stage };
    }));
  };

  // ---- editor actions ----
  const updateEditor = (id, patch) => setEditors(p => p.map(e => e.id === id ? { ...e, ...patch } : e));
  const addEditor = (name, level, jobTitle = "Editor", normHours = NORM_HOURS) => {
    const color = AVATAR_COLORS[editors.length % AVATAR_COLORS.length];
    const e = { id: "ed" + (editors.length + 1) + "_" + Date.now(), name, level, color, jobTitle, normHours,
      actualHours: 0, products: 0, hiStar: 0, onTime: 0, trend: [0,0,0,0,0,0], activeTasks: 0 };
    setEditors(p => [...p, e]);
    notify({ icon: "users", text: `👤 Đã thêm <b>${name}</b> (${level} · ${jobTitle}) — định mức ${normHours}h/kỳ.` });
  };

  const openEditor = (id) => setEditorDetail(id);

  const ctx = {
    role, persona, route, editors, orders, editorById,
    go, createOrder, intakeOrder, moveOrder, acceptOrder, updateOrder, addFeedback,
    updateEditor, addEditor, openEditor, notify, handleLogout,
  };

  // ---- render current screen ----
  const screen = () => {
    switch (route) {
      case "new": return <OrderForm />;
      case "orders": return <MyOrders />;
      case "myboard": return <KanbanBoard scope={persona.editorId} />;
      case "mykpi": return <EditorKPI ed={editorById(persona.editorId)} />;
      case "dashboard": return <Dashboard />;
      case "intake": return <IntakeQueue />;
      case "board": return <KanbanBoard scope="team" />;
      case "staff": return <StaffManagement />;
      default: return null;
    }
  };

  const nav = NAV[role];
  const [pt, ps] = PAGE_META[route] || ["", ""];
  const navCount = (k) => {
    if (k === "intake") return orders.filter(o => o.stage === "intake").length;
    if (k === "orders") return orders.filter(o => o.requester === persona.name && o.stage === "review").length || null;
    if (k === "myboard") return orders.filter(o => o.editorId === persona.editorId && o.stage !== "done").length;
    return null;
  };

  return (
    <AppCtx.Provider value={ctx}>
      <div className="app">
        {navOpen && <div className="scrim-mobile" onClick={() => setNavOpen(false)} />}
        <aside className={"sidebar" + (navOpen ? " open" : "")}>
          <div className="brand">
            <div className="brand-mark"><Icon name="film" size={20} /></div>
            <div><div className="brand-name">Media SOP</div><div className="brand-sub">Quy trình sản xuất</div></div>
          </div>

          <div className="nav-group-label">{persona.title}</div>
          {nav.map(item => {
            const c = navCount(item.key);
            return (
              <button key={item.key} className={"nav-item" + (route === item.key ? " active" : "")} onClick={() => go(item.key)}>
                <Icon name={item.icon} size={19} />{item.label}
                {c ? <span className="nav-count">{c}</span> : null}
              </button>
            );
          })}

          <div className="nav-group-label">Quy trình 7 bước</div>
          <div style={{ padding: "2px 12px" }}>
            {["Gửi order","Tiếp nhận & Estimate","Thực hiện","Feedback & Sửa","Nghiệm thu","Lưu trữ","Báo cáo KPI"].map((s, i) => (
              <div key={i} className="row" style={{ gap: 9, padding: "5px 0", fontSize: 12, color: "oklch(0.72 0.03 290)" }}>
                <span style={{ width: 18, height: 18, borderRadius: 50, background: "oklch(0.30 0.05 290)", display: "grid", placeItems: "center", fontSize: 10, fontWeight: 700, flex: "0 0 auto", color: "oklch(0.85 0.04 290)" }}>{i+1}</span>
                {s}
              </div>
            ))}
          </div>

          <div className="sidebar-footer">
            <div className="persona">
              <Avatar name={persona.name} color={persona.color || "linear-gradient(135deg,var(--violet-400),var(--pink))"} size={38} />
              <div className="pcol"><div className="pname">{persona.name}</div><div className="prole">{persona.dept}</div></div>
            </div>
          </div>
        </aside>

        <div className="main">
          <div className="topbar">
            <button className="icon-btn menu-btn" onClick={() => setNavOpen(true)}><Icon name="menu" size={22} /></button>
            <div>
              <div className="page-title">{pt}</div>
              <div className="page-sub">{ps}</div>
            </div>
            <div className="topbar-spacer" />
            <div className="row" style={{ gap: 8, alignItems: "center" }}>
              <div className="role-badge">
                <Icon name={role === "order" ? "order" : role === "editor" ? "video" : "briefcase"} size={14} />
                <span>{persona.title}</span>
              </div>
              <button className="icon-btn" title="Đăng xuất" onClick={handleLogout}
                style={{ width: 36, height: 36, borderRadius: 10, color: "oklch(0.60 0.05 290)" }}>
                <Icon name="logout" size={18} />
              </button>
            </div>
            <button className="icon-btn" style={{ position: "relative", width: 40, height: 40 }} onClick={() => setTgOpen(true)} title="Thông báo Telegram">
              <Icon name="bell" size={20} />
              {notifs.length > 0 && <span style={{ position: "absolute", top: 6, right: 6, minWidth: 16, height: 16, padding: "0 4px", borderRadius: 10, background: "var(--pink)", color: "white", fontSize: 10, fontWeight: 700, display: "grid", placeItems: "center" }}>{notifs.length}</span>}
            </button>
          </div>

          <div className="content">{screen()}</div>
        </div>

        {tgOpen && <TelegramPanel notifications={notifs} onClose={() => setTgOpen(false)} />}
        <Toasts toasts={toasts} />
        {editorDetail && <EditorDetail ed={editorById(editorDetail)} onClose={() => setEditorDetail(null)} />}
      </div>
    </AppCtx.Provider>
  );
}

// editor's own KPI view (reuse EditorDetail content inline)
function EditorKPI({ ed }) {
  const app = window.useApp();
  const p = performance(ed), band = perfBand(p);
  const done = app.orders.filter(o => o.editorId === ed.id && o.stage === "done");
  return (
    <div className="content-narrow">
      <div className="card rise" style={{ background: "linear-gradient(115deg, oklch(0.30 0.10 290), oklch(0.45 0.20 295))", color: "white", padding: 26, marginBottom: 22, border: "none" }}>
        <div className="row between wrap" style={{ gap: 20 }}>
          <div className="row" style={{ gap: 16 }}>
            <Avatar name={ed.name} color={ed.color} size={56} fontSize={20} />
            <div>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 24 }}>{ed.name}</div>
              <div className="row" style={{ gap: 8, marginTop: 4 }}><span className="badge" style={{ background: "oklch(1 0 0 / 0.2)", color: "white" }}>{ed.level}</span><span className={"band " + band.cls}>{band.label}</span></div>
            </div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ opacity: 0.8, fontSize: 13 }}>KPI tổng hợp</div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 44, lineHeight: 1 }}>{pct(kpiScore(ed))}</div>
          </div>
        </div>
      </div>
      <div className="grid g-3" style={{ marginBottom: 22 }}>
        <div className="stat" style={{ textAlign: "center", padding: 20 }}><Ring value={Math.min(1, p)} size={88} color="var(--violet-500)" label={pct(p)+"%"} /><div className="stat-label" style={{ marginTop: 10 }}>Hiệu suất ({ed.actualHours}/{normOf(ed)}h)</div></div>
        <div className="stat" style={{ textAlign: "center", padding: 20 }}><Ring value={qualityScore(ed)} size={88} color="var(--amber)" track="var(--amber-bg)" label={pct(qualityScore(ed))+"%"} /><div className="stat-label" style={{ marginTop: 10 }}>Chất lượng ({ed.hiStar}/{ed.products} ≥4★)</div></div>
        <div className="stat" style={{ textAlign: "center", padding: 20 }}><Ring value={deadlineScore(ed)} size={88} color="var(--cyan)" track="var(--cyan-bg)" label={pct(deadlineScore(ed))+"%"} /><div className="stat-label" style={{ marginTop: 10 }}>Deadline ({ed.onTime}/{ed.products})</div></div>
      </div>
      <div className="grid g-2">
        <div className="card card-pad"><div className="card-h"><div className="brand-mark" style={{ width: 34, height: 34, borderRadius: 9 }}><Icon name="trendUp" size={16} /></div><h3>Hiệu suất 6 tháng</h3></div><BarChart data={ed.trend} height={120} baseline={100} /></div>
        <div className="card card-pad"><div className="card-h"><div className="brand-mark" style={{ width: 34, height: 34, borderRadius: 9 }}><Icon name="film" size={16} /></div><h3>Sản phẩm hoàn tất</h3></div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {done.map(o => <div key={o.id} className="row between card" style={{ padding: "9px 12px", borderRadius: 11 }}><span className="row" style={{ gap: 8 }}><VChip vtype={o.vtype} /><span style={{ fontSize: 12.5, fontWeight: 600 }}>{o.title}</span></span>{o.rating && <Stars value={o.rating} size={13} />}</div>)}
            {done.length === 0 && <div className="hint">Chưa có sản phẩm hoàn tất.</div>}
          </div>
        </div>
      </div>
    </div>
  );
}

window.App = App;
ReactDOM.createRoot(document.getElementById("root")).render(
  <AuthGate><App /></AuthGate>
);
