const { useState, useEffect, useRef } = React;

// ─── AI ───────────────────────────────────────────────────────────────────────
async function ai(prompt, system = "") {
  const r = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "claude-sonnet-4-20250514", max_tokens: 1000,
      ...(system && { system }),
      messages: [{ role: "user", content: prompt }],
    }),
  });
  const d = await r.json();
  return (d?.content || []).filter(b => b.type === "text").map(b => b.text).join("");
}

// ─── Design ───────────────────────────────────────────────────────────────────
const C = {
  bg:      "#0B0C10",
  sidebar: "#0F1117",
  surface: "#13151C",
  card:    "#181B24",
  cardHov: "#1E2230",
  border:  "#22263A",
  borderL: "#2A2F45",
  gold:    "#F0A832",
  goldD:   "rgba(240,168,50,0.1)",
  goldG:   "rgba(240,168,50,0.06)",
  violet:  "#7C6AFF",
  violetD: "rgba(124,106,255,0.12)",
  teal:    "#00D4AA",
  tealD:   "rgba(0,212,170,0.1)",
  red:     "#FF4D6A",
  redD:    "rgba(255,77,106,0.1)",
  blue:    "#4D8EFF",
  blueD:   "rgba(77,142,255,0.1)",
  text:    "#E8ECF4",
  muted:   "#5A6180",
  dim:     "#252840",
};

const css = `
@import url('https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700;800&family=DM+Sans:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap');
*{box-sizing:border-box;margin:0;padding:0;}
html,body,#root{height:100%;overflow:hidden;background:${C.bg};}
::-webkit-scrollbar{width:3px;height:3px;}
::-webkit-scrollbar-thumb{background:${C.border};border-radius:2px;}
button{cursor:pointer;border:none;background:none;font-family:inherit;}
input,textarea,select{outline:none;font-family:inherit;}
@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
@keyframes pulse{0%,100%{opacity:.4}50%{opacity:1}}
@keyframes spin{to{transform:rotate(360deg)}}
@keyframes glow{0%,100%{box-shadow:0 0 10px ${C.gold}33}50%{box-shadow:0 0 22px ${C.gold}66}}
@keyframes slideIn{from{opacity:0;transform:translateX(-10px)}to{opacity:1;transform:translateX(0)}}
@keyframes blink{0%,100%{opacity:1}50%{opacity:.2}}
.fade{animation:fadeUp .35s ease forwards;}
.slide{animation:slideIn .3s ease forwards;}
`;

// ─── Icons ────────────────────────────────────────────────────────────────────
const Icon = ({ name, size = 16, color = C.muted }) => {
  const icons = {
    dashboard:  "M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z",
    tasks:      "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z",
    calendar:   "M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 18H4V8h16v13z",
    brain:      "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z",
    files:      "M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2z",
    bell:       "M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z",
    settings:   "M12 15.5A3.5 3.5 0 018.5 12 3.5 3.5 0 0112 8.5a3.5 3.5 0 013.5 3.5 3.5 3.5 0 01-3.5 3.5m7.43-2.92c.04-.36.07-.73.07-1.08s-.03-.73-.07-1.08l2.33-1.82c.21-.16.27-.45.13-.69l-2.2-3.81c-.14-.24-.43-.32-.67-.24l-2.75 1.1c-.57-.44-1.18-.8-1.85-1.08L14.4 2.81C14.36 2.54 14.12 2.34 13.84 2.34H10.16c-.28 0-.52.2-.56.47L9.21 5.47C8.54 5.75 7.93 6.11 7.36 6.55L4.61 5.45c-.24-.09-.53 0-.67.24L1.74 9.5c-.14.24-.07.53.13.69l2.33 1.82c-.04.35-.07.72-.07 1.08s.03.73.07 1.08L1.87 15.99c-.21.16-.27.45-.13.69l2.2 3.81c.14.24.43.32.67.24l2.75-1.1c.57.44 1.18.8 1.85 1.08l.39 2.66c.04.27.28.47.56.47h3.68c.28 0 .52-.2.56-.47l.39-2.66c.67-.28 1.28-.64 1.85-1.08l2.75 1.1c.24.09.53 0 .67-.24l2.2-3.81c.14-.24.07-.53-.13-.69l-2.33-1.82z",
    star:       "M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z",
    workflow:   "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 14H7v-2h5v2zm5-4H7v-2h10v2zm0-4H7V7h10v2z",
    search:     "M15.5 14h-.79l-.28-.27A6.471 6.471 0 0016 9.5 6.5 6.5 0 109.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z",
    plus:       "M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z",
    check:      "M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z",
    arrow:      "M8 5v14l11-7z",
    close:      "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z",
    ai:         "M21 3L3 10.53v.98l6.84 2.65L12.48 21h.98L21 3z",
    fire:       "M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 17.41 3.8 13.5.67z",
    link:       "M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1 0 1.71-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z",
    dot:        "M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z",
    focus:      "M7 7H5v3H3V5h4v2zm3-2h4V3h-4v2zm4 12h-4v2h4v-2zm-4-2H5v-3H3v4h4v-2zm10-8h-2v3h-2V5h4v2zm-2 8h2v4h-4v-2h2v-2zM3 13H1v-2h2v2zm18-2v2h2v-2h-2zM11 13H9v-2h2v2zm2-2h2v2h-2v-2zm0-4H9V5h4v2z",
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} style={{ flexShrink: 0 }}>
      <path d={icons[name] || icons.dot} />
    </svg>
  );
};

// ─── Atoms ────────────────────────────────────────────────────────────────────
const Mono = ({ c = C.muted, s = 10, children }) => (
  <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: s, color: c, letterSpacing: .5 }}>{children}</span>
);

const Badge = ({ label, color = C.gold }) => (
  <span style={{ background: color + "22", color, border: `1px solid ${color}44`, borderRadius: 4, padding: "2px 7px", fontSize: 10, fontWeight: 600, fontFamily: "'JetBrains Mono',monospace" }}>{label}</span>
);

const Tag = ({ label, color = C.gold }) => (
  <span style={{ background: color + "18", color, borderRadius: 20, padding: "2px 10px", fontSize: 11, fontWeight: 600 }}>{label}</span>
);

const Spinner = ({ size = 16 }) => (
  <div style={{ width: size, height: size, border: `2px solid ${C.border}`, borderTopColor: C.gold, borderRadius: "50%", animation: "spin .7s linear infinite" }} />
);

// ─── Seed Data ────────────────────────────────────────────────────────────────
const TASKS = [
  { id: 1, title: "Follow up Dmitry — Chaweng Noi viewing", priority: "urgent", status: "todo", project: "Property Deals", due: "Today", assignee: "J" },
  { id: 2, title: "Send lease agreement to Sarah", priority: "high", status: "doing", project: "Property Deals", due: "Tomorrow", assignee: "Fon" },
  { id: 3, title: "Update property photos — Thaledi", priority: "medium", status: "todo", project: "Thaledi Commercial", due: "Apr 8", assignee: "Ann" },
  { id: 4, title: "Call accountant — Q1 financials", priority: "high", status: "done", project: "Finance", due: "Done", assignee: "J" },
  { id: 5, title: "Prepare contract template", priority: "medium", status: "todo", project: "Property Deals", due: "Apr 9", assignee: "J" },
  { id: 6, title: "Schedule site visit — new client", priority: "low", status: "todo", project: "Business Dev", due: "Apr 10", assignee: "Mike" },
];

const PROJECTS = [
  { id: 1, name: "Property Deals", icon: "🏠", tasks: 8, done: 5, color: C.gold, insight: "Dmitry hasn't been followed up in 2 days", risk: true },
  { id: 2, name: "Thaledi Commercial", icon: "🏢", tasks: 5, done: 2, color: C.violet, insight: "3 photos pending before listing goes live", risk: false },
  { id: 3, name: "Business Dev", icon: "🚀", tasks: 4, done: 1, color: C.teal, insight: "New lead from Lamai — follow up needed", risk: false },
  { id: 4, name: "Finance", icon: "💰", tasks: 3, done: 3, color: C.blue, insight: "All tasks complete for this week", risk: false },
];

const CALENDAR_EVENTS = [
  { time: "09:00", title: "Call with Dmitry", type: "meeting", color: C.gold },
  { time: "11:30", title: "Property viewing — Chaweng", type: "visit", color: C.teal },
  { time: "14:00", title: "Team check-in", type: "meeting", color: C.violet },
  { time: "16:30", title: "Review lease agreement", type: "task", color: C.blue },
];

const ACTIVITY = [
  { icon: "✅", text: "Task completed: Call accountant", time: "10 min ago", color: C.green },
  { icon: "📝", text: "Note saved: Dmitry negotiation terms", time: "1 hour ago", color: C.gold },
  { icon: "📅", text: "Meeting added: Property viewing 11:30", time: "2 hours ago", color: C.violet },
  { icon: "🏠", text: "New listing: Chaweng Noi — ฿45k/mo", time: "Yesterday", color: C.teal },
  { icon: "🤖", text: "AI flagged: Thaledi deal may be delayed", time: "Yesterday", color: C.red },
];

const P_COLORS = { urgent: C.red, high: C.gold, medium: C.blue, low: C.muted };
const S_COLORS = { todo: C.muted, doing: C.gold, done: C.teal };

// ─── SIDEBAR ──────────────────────────────────────────────────────────────────
const NAV = [
  { id: "dashboard", icon: "dashboard", label: "Dashboard" },
  { id: "tasks",     icon: "tasks",     label: "Tasks" },
  { id: "projects",  icon: "workflow",  label: "Projects" },
  { id: "calendar",  icon: "calendar",  label: "Calendar" },
  { id: "ai",        icon: "brain",     label: "AI Assistant" },
  { id: "knowledge", icon: "files",     label: "Knowledge" },
];

function Sidebar({ active, setActive, notifications }) {
  return (
    <div style={{ width: 220, background: C.sidebar, borderRight: `1px solid ${C.border}`, display: "flex", flexDirection: "column", flexShrink: 0 }}>
      {/* Logo */}
      <div style={{ padding: "20px 18px 16px", borderBottom: `1px solid ${C.border}` }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: 9, background: `linear-gradient(135deg, ${C.gold}, ${C.violet})`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, boxShadow: `0 4px 14px ${C.gold}44` }}>🌴</div>
          <div>
            <div style={{ color: C.text, fontSize: 14, fontFamily: "'Syne',sans-serif", fontWeight: 800, letterSpacing: 1 }}>CHOWTO</div>
            <Mono c={C.muted} s={9}>OPS SYSTEM</Mono>
          </div>
        </div>
      </div>

      {/* Nav */}
      <div style={{ flex: 1, padding: "12px 10px", display: "flex", flexDirection: "column", gap: 2, overflowY: "auto" }}>
        <Mono c={C.muted} s={9} style={{ padding: "6px 8px 4px" }}>GENERAL</Mono>
        {NAV.map(n => (
          <button key={n.id} onClick={() => setActive(n.id)} style={{
            display: "flex", alignItems: "center", gap: 10, padding: "9px 10px", borderRadius: 8,
            background: active === n.id ? C.goldG : "transparent",
            border: `1px solid ${active === n.id ? C.gold + "33" : "transparent"}`,
            color: active === n.id ? C.gold : C.muted,
            fontSize: 13, fontFamily: "'DM Sans',sans-serif", fontWeight: active === n.id ? 500 : 400,
            transition: "all .15s", textAlign: "left", width: "100%",
          }}>
            <Icon name={n.icon} size={15} color={active === n.id ? C.gold : C.muted} />
            <span style={{ flex: 1 }}>{n.label}</span>
            {n.id === "tasks" && <Badge label="6" color={C.red} />}
            {n.id === "ai" && <div style={{ width: 7, height: 7, borderRadius: "50%", background: C.teal, animation: "blink 2s infinite" }} />}
          </button>
        ))}

        <div style={{ marginTop: 16, borderTop: `1px solid ${C.border}`, paddingTop: 10 }}>
          <Mono c={C.muted} s={9} style={{ padding: "4px 8px" }}>FAVOURITES</Mono>
          {["Property Deals", "Thaledi Commercial"].map(f => (
            <button key={f} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 10px", borderRadius: 8, color: C.muted, fontSize: 12, textAlign: "left", width: "100%" }}>
              <span style={{ color: C.gold, fontSize: 12 }}>★</span> {f}
            </button>
          ))}
        </div>
      </div>

      {/* User */}
      <div style={{ padding: "12px 14px", borderTop: `1px solid ${C.border}`, display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ width: 32, height: 32, borderRadius: "50%", background: `linear-gradient(135deg, ${C.gold}cc, ${C.gold}66)`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 800, color: C.bg }}>J</div>
        <div>
          <div style={{ color: C.text, fontSize: 12, fontWeight: 600 }}>J</div>
          <div style={{ color: C.teal, fontSize: 10, fontFamily: "'JetBrains Mono',monospace" }}>● online · Koh Samui</div>
        </div>
      </div>
    </div>
  );
}

// ─── STAT CARD ────────────────────────────────────────────────────────────────
function StatCard({ icon, label, value, sub, color, onClick }) {
  return (
    <div onClick={onClick} style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: "16px 18px", cursor: onClick ? "pointer" : "default", transition: "border-color .15s" }}
      onMouseEnter={e => e.currentTarget.style.borderColor = color + "55"}
      onMouseLeave={e => e.currentTarget.style.borderColor = C.border}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 10 }}>
        <div style={{ width: 34, height: 34, borderRadius: 9, background: color + "18", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16 }}>{icon}</div>
        {sub && <Mono c={sub.includes("↑") ? C.teal : C.red} s={10}>{sub}</Mono>}
      </div>
      <div style={{ color, fontSize: 28, fontFamily: "'Syne',sans-serif", fontWeight: 800, lineHeight: 1 }}>{value}</div>
      <div style={{ color: C.muted, fontSize: 12, marginTop: 4 }}>{label}</div>
    </div>
  );
}

// ─── DASHBOARD ────────────────────────────────────────────────────────────────
function Dashboard({ setActive }) {
  const [aiGreeting, setAiGreeting] = useState("Loading your morning briefing...");
  const [aiLoading, setAiLoading] = useState(true);
  const [focusMode, setFocusMode] = useState(false);
  const [focusProject, setFocusProject] = useState(null);

  const hour = new Date().getHours();
  const greet = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening";
  const today = new Date().toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" });
  const pending = TASKS.filter(t => t.status !== "done").length;
  const urgent  = TASKS.filter(t => t.priority === "urgent" && t.status !== "done").length;

  useEffect(() => {
    ai(`You are an AI secretary for CHOWTO property management on Koh Samui. Write a sharp 2-sentence morning briefing for J. Urgent tasks: ${urgent}. Pending: ${pending}. Most important: follow up Russian client Dmitry about property viewing. Be direct, actionable.`)
      .then(t => { setAiGreeting(t); setAiLoading(false); });
  }, []);

  if (focusMode && focusProject) {
    const proj = PROJECTS.find(p => p.id === focusProject);
    const projTasks = TASKS.filter(t => t.project === proj.name);
    return (
      <div style={{ padding: 28, display: "flex", flexDirection: "column", gap: 20 }} className="fade">
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <button onClick={() => { setFocusMode(false); setFocusProject(null); }} style={{ color: C.muted, fontSize: 13, display: "flex", alignItems: "center", gap: 6 }}>← Back</button>
          <div style={{ color: C.text, fontSize: 22, fontFamily: "'Syne',sans-serif", fontWeight: 800 }}>{proj.icon} {proj.name}</div>
          <Tag label="FOCUS MODE" color={proj.color} />
        </div>
        <div style={{ background: proj.color + "12", border: `1px solid ${proj.color}33`, borderRadius: 12, padding: 14 }}>
          <Mono c={proj.color} s={10}>🤖 AI INSIGHT</Mono>
          <div style={{ color: C.text, fontSize: 13, marginTop: 6, lineHeight: 1.6 }}>{proj.insight}</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <Mono c={C.muted} s={10}>TASKS ({projTasks.length})</Mono>
          {projTasks.map(t => (
            <div key={t.id} style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 10, padding: "12px 14px", display: "flex", gap: 10, alignItems: "center" }}>
              <div style={{ width: 8, height: 8, borderRadius: "50%", background: P_COLORS[t.priority], flexShrink: 0 }} />
              <span style={{ color: t.status === "done" ? C.muted : C.text, flex: 1, fontSize: 13, textDecoration: t.status === "done" ? "line-through" : "none" }}>{t.title}</span>
              <Badge label={t.status} color={S_COLORS[t.status]} />
              <Badge label={t.due} color={C.muted} />
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding: "24px 28px", display: "flex", flexDirection: "column", gap: 22, overflowY: "auto" }} className="fade">
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div style={{ color: C.muted, fontSize: 12, marginBottom: 4 }}>{today}</div>
          <div style={{ fontSize: 26, fontFamily: "'Syne',sans-serif", fontWeight: 800, color: C.text }}>{greet}, <span style={{ color: C.gold }}>J</span> 🌴</div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button onClick={() => setActive("ai")} style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 8, background: C.violetD, border: `1px solid ${C.violet}44`, color: C.violet, fontSize: 12, fontWeight: 600 }}>
            🤖 Ask AI
          </button>
          <button style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 8, background: C.goldD, border: `1px solid ${C.gold}44`, color: C.gold, fontSize: 12, fontWeight: 600 }}>
            <Icon name="focus" size={14} color={C.gold} /> Focus Mode
          </button>
        </div>
      </div>

      {/* AI Briefing */}
      <div style={{ background: `linear-gradient(135deg, ${C.card}, #1A1D2A)`, border: `1px solid ${C.gold}33`, borderRadius: 14, padding: "16px 18px" }}>
        <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
          <div style={{ width: 34, height: 34, borderRadius: 9, background: C.goldD, border: `1px solid ${C.gold}44`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, flexShrink: 0, animation: aiLoading ? "glow 2s infinite" : "none" }}>🧠</div>
          <div>
            <Mono c={C.gold} s={10}>AI MORNING BRIEFING</Mono>
            <div style={{ color: aiLoading ? C.muted : C.text, fontSize: 13, marginTop: 6, lineHeight: 1.7 }}>
              {aiLoading ? <span style={{ animation: "pulse 1.5s infinite" }}>Analysing your day...</span> : aiGreeting}
            </div>
          </div>
        </div>
      </div>

      {/* Stats */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <StatCard icon="✅" label="Pending Tasks" value={pending} sub="↑ 2 new" color={C.gold} onClick={() => setActive("tasks")} />
        <StatCard icon="🔥" label="Urgent" value={urgent} color={C.red} />
        <StatCard icon="📅" label="Today's Meetings" value={2} color={C.violet} onClick={() => setActive("calendar")} />
        <StatCard icon="🏠" label="Active Deals" value={3} sub="↑ 1 new" color={C.teal} onClick={() => setActive("projects")} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
        {/* Projects */}
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <Mono c={C.muted} s={10}>PROJECTS</Mono>
            <button onClick={() => setActive("projects")} style={{ color: C.blue, fontSize: 11 }}>View all →</button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {PROJECTS.slice(0, 3).map(p => (
              <div key={p.id} style={{ background: C.card, border: `1px solid ${p.risk ? C.red + "44" : C.border}`, borderRadius: 12, padding: "13px 15px", cursor: "pointer", transition: "all .15s" }}
                onMouseEnter={e => e.currentTarget.style.borderColor = p.color + "66"}
                onMouseLeave={e => e.currentTarget.style.borderColor = p.risk ? C.red + "44" : C.border}
                onClick={() => { setFocusMode(true); setFocusProject(p.id); }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <span style={{ fontSize: 16 }}>{p.icon}</span>
                    <span style={{ color: C.text, fontSize: 13, fontWeight: 600 }}>{p.name}</span>
                  </div>
                  {p.risk && <Badge label="risk" color={C.red} />}
                </div>
                <div style={{ height: 3, background: C.dim, borderRadius: 2, marginBottom: 6 }}>
                  <div style={{ height: "100%", width: `${(p.done / p.tasks) * 100}%`, background: p.color, borderRadius: 2, transition: "width 1s ease" }} />
                </div>
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                  <Mono c={C.muted} s={9}>{p.done}/{p.tasks} tasks</Mono>
                  <div style={{ color: p.color, fontSize: 10, maxWidth: "65%", textAlign: "right" }}>💡 {p.insight}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Activity + AI Suggestions */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {/* AI Suggestions */}
          <div style={{ background: C.card, border: `1px solid ${C.violet}33`, borderRadius: 12, padding: "13px 15px" }}>
            <Mono c={C.violet} s={10}>🤖 AI SUGGESTIONS</Mono>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 10 }}>
              {["Follow up Dmitry — 2 days no contact", "Thaledi listing — photos still missing", "Sarah's contract — review before sending"].map((s, i) => (
                <div key={i} style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
                  <div style={{ width: 18, height: 18, borderRadius: "50%", background: C.violetD, border: `1px solid ${C.violet}44`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 9, color: C.violet, flexShrink: 0, marginTop: 1 }}>{i + 1}</div>
                  <span style={{ color: C.text, fontSize: 12, lineHeight: 1.5 }}>{s}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Activity */}
          <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 12, padding: "13px 15px", flex: 1 }}>
            <Mono c={C.muted} s={10}>ACTIVITY FEED</Mono>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 10 }}>
              {ACTIVITY.slice(0, 4).map((a, i) => (
                <div key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                  <span style={{ fontSize: 14, flexShrink: 0 }}>{a.icon}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ color: C.text, fontSize: 12, lineHeight: 1.4 }}>{a.text}</div>
                    <Mono c={C.muted} s={9}>{a.time}</Mono>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── TASKS VIEW ────────────────────────────────────────────────────────────────
function Tasks() {
  const [tasks, setTasks] = useState(TASKS);
  const [filter, setFilter] = useState("all");
  const [showAdd, setShowAdd] = useState(false);
  const [newTask, setNewTask] = useState({ title: "", priority: "medium", project: "Property Deals", due: "" });
  const [aiLoading, setAiLoading] = useState(false);
  const [selected, setSelected] = useState(null);

  const toggle = (id) => setTasks(prev => prev.map(t => t.id === id ? { ...t, status: t.status === "done" ? "todo" : "done" } : t));
  const filtered = filter === "all" ? tasks : filter === "done" ? tasks.filter(t => t.status === "done") : tasks.filter(t => t.priority === filter || t.status === filter);

  const aiPrioritize = async () => {
    setAiLoading(true);
    await new Promise(r => setTimeout(r, 1200));
    setTasks(prev => [...prev].sort((a, b) => {
      const o = { urgent: 0, high: 1, medium: 2, low: 3 };
      return o[a.priority] - o[b.priority];
    }));
    setAiLoading(false);
  };

  return (
    <div style={{ padding: "24px 28px", display: "flex", flexDirection: "column", gap: 18, overflowY: "auto" }} className="fade">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div>
          <div style={{ color: C.text, fontSize: 22, fontFamily: "'Syne',sans-serif", fontWeight: 800 }}>Tasks</div>
          <Mono c={C.muted} s={10}>{tasks.filter(t => t.status !== "done").length} pending · {tasks.filter(t => t.priority === "urgent" && t.status !== "done").length} urgent</Mono>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button onClick={aiPrioritize} disabled={aiLoading} style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 8, background: C.violetD, border: `1px solid ${C.violet}44`, color: C.violet, fontSize: 12, fontWeight: 600, opacity: aiLoading ? .6 : 1 }}>
            {aiLoading ? <Spinner size={12} /> : "🤖"} AI Sort
          </button>
          <button onClick={() => setShowAdd(v => !v)} style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 8, background: C.gold, color: C.bg, fontSize: 12, fontWeight: 700 }}>
            + New Task
          </button>
        </div>
      </div>

      {/* Filter */}
      <div style={{ display: "flex", gap: 6 }}>
        {["all", "urgent", "high", "doing", "todo", "done"].map(f => (
          <button key={f} onClick={() => setFilter(f)} style={{ padding: "5px 13px", borderRadius: 20, fontSize: 11, fontWeight: 600, background: filter === f ? C.gold + "1A" : C.surface, border: `1px solid ${filter === f ? C.gold + "55" : C.border}`, color: filter === f ? C.gold : C.muted }}>
            {f}
          </button>
        ))}
      </div>

      {/* Add form */}
      {showAdd && (
        <div style={{ background: C.card, border: `1px solid ${C.gold}44`, borderRadius: 12, padding: 16, display: "flex", flexDirection: "column", gap: 10 }} className="fade">
          <input value={newTask.title} onChange={e => setNewTask(p => ({ ...p, title: e.target.value }))} placeholder="Task title..."
            style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 8, color: C.text, padding: "9px 12px", fontSize: 13, width: "100%" }} autoFocus />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
            {["urgent", "high", "medium", "low"].slice(0, 3).map(p => (
              <button key={p} onClick={() => setNewTask(prev => ({ ...prev, priority: p }))} style={{ padding: "7px", borderRadius: 8, fontSize: 11, fontWeight: 600, background: newTask.priority === p ? P_COLORS[p] + "22" : C.surface, border: `1px solid ${newTask.priority === p ? P_COLORS[p] + "66" : C.border}`, color: newTask.priority === p ? P_COLORS[p] : C.muted }}>
                {p}
              </button>
            ))}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => { if (newTask.title) { setTasks(p => [...p, { ...newTask, id: Date.now(), status: "todo", assignee: "J" }]); setNewTask({ title: "", priority: "medium", project: "Property Deals", due: "" }); setShowAdd(false); } }} style={{ padding: "9px 18px", borderRadius: 8, background: C.gold, color: C.bg, fontSize: 13, fontWeight: 700 }}>Add</button>
            <button onClick={() => setShowAdd(false)} style={{ padding: "9px 18px", borderRadius: 8, background: C.surface, border: `1px solid ${C.border}`, color: C.muted, fontSize: 13 }}>Cancel</button>
          </div>
        </div>
      )}

      {/* Task list */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {filtered.map(t => (
          <div key={t.id} style={{ background: C.card, border: `1px solid ${selected === t.id ? C.gold + "66" : C.border}`, borderRadius: 12, padding: "13px 15px", borderLeft: `3px solid ${P_COLORS[t.priority]}`, cursor: "pointer", transition: "all .15s" }}
            onClick={() => setSelected(selected === t.id ? null : t.id)}>
            <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
              <button onClick={e => { e.stopPropagation(); toggle(t.id); }} style={{ width: 20, height: 20, borderRadius: 6, border: `2px solid ${t.status === "done" ? C.teal : P_COLORS[t.priority]}`, background: t.status === "done" ? C.teal : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, transition: "all .2s" }}>
                {t.status === "done" && <Icon name="check" size={12} color="#fff" />}
              </button>
              <span style={{ flex: 1, color: t.status === "done" ? C.muted : C.text, fontSize: 13, fontWeight: 500, textDecoration: t.status === "done" ? "line-through" : "none" }}>{t.title}</span>
              <Badge label={t.priority} color={P_COLORS[t.priority]} />
              <Badge label={t.project} color={C.blue} />
              <Badge label={t.due} color={C.muted} />
              <div style={{ width: 22, height: 22, borderRadius: "50%", background: C.gold + "22", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, color: C.gold, fontWeight: 700 }}>{t.assignee[0]}</div>
            </div>
            {selected === t.id && (
              <div style={{ marginTop: 12, padding: "10px 12px", background: C.violetD, border: `1px solid ${C.violet}33`, borderRadius: 8 }} className="fade">
                <Mono c={C.violet} s={10}>🤖 AI INSIGHT</Mono>
                <div style={{ color: C.text, fontSize: 12, marginTop: 4, lineHeight: 1.5 }}>
                  {t.priority === "urgent" ? "This task is overdue. Immediate action required — contact client within the next 2 hours." : "On track. Consider delegating if bandwidth is low."}
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── CALENDAR ─────────────────────────────────────────────────────────────────
function Calendar() {
  const days = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
  const today = new Date().getDate();
  const dates = Array.from({ length: 30 }, (_, i) => i + 1);

  return (
    <div style={{ padding: "24px 28px", display: "flex", flexDirection: "column", gap: 20, overflowY: "auto" }} className="fade">
      <div style={{ color: C.text, fontSize: 22, fontFamily: "'Syne',sans-serif", fontWeight: 800 }}>Calendar</div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 20 }}>
        {/* Timeline today */}
        <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: "16px 18px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 16 }}>
            <Mono c={C.muted} s={10}>TODAY'S TIMELINE</Mono>
            <button style={{ display: "flex", alignItems: "center", gap: 5, color: C.gold, fontSize: 11, fontWeight: 600, background: C.goldD, border: `1px solid ${C.gold}33`, padding: "4px 10px", borderRadius: 6 }}>+ Add Event</button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {CALENDAR_EVENTS.map((e, i) => (
              <div key={i} style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
                <Mono c={C.muted} s={11}>{e.time}</Mono>
                <div style={{ flex: 1, background: e.color + "12", border: `1px solid ${e.color}33`, borderRadius: 8, padding: "10px 12px", borderLeft: `3px solid ${e.color}` }}>
                  <div style={{ color: C.text, fontSize: 13, fontWeight: 500 }}>{e.title}</div>
                  <Tag label={e.type} color={e.color} />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Mini calendar */}
        <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: "16px 18px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
            <div style={{ color: C.text, fontSize: 14, fontWeight: 600 }}>April 2026</div>
            <div style={{ display: "flex", gap: 8 }}>
              <button style={{ color: C.muted, fontSize: 16 }}>←</button>
              <button style={{ color: C.muted, fontSize: 16 }}>→</button>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4, marginBottom: 8 }}>
            {days.map(d => <Mono key={d} c={C.muted} s={10} style={{ textAlign: "center" }}>{d}</Mono>)}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4 }}>
            {dates.map(d => (
              <button key={d} style={{ aspectRatio: 1, borderRadius: 8, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, background: d === today ? C.gold : "transparent", color: d === today ? C.bg : d === 6 || d === 8 ? C.gold : C.muted, fontWeight: d === today ? 700 : 400, border: d === 6 || d === 8 ? `1px solid ${C.gold}44` : "none" }}>
                {d}
              </button>
            ))}
          </div>

          {/* Upcoming */}
          <div style={{ marginTop: 16, borderTop: `1px solid ${C.border}`, paddingTop: 12 }}>
            <Mono c={C.muted} s={9}>UPCOMING</Mono>
            {CALENDAR_EVENTS.slice(0, 3).map((e, i) => (
              <div key={i} style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 8 }}>
                <div style={{ width: 6, height: 6, borderRadius: "50%", background: e.color, flexShrink: 0 }} />
                <span style={{ color: C.text, fontSize: 11 }}>{e.title}</span>
                <Mono c={C.muted} s={9}>{e.time}</Mono>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── AI ASSISTANT ─────────────────────────────────────────────────────────────
function AIAssistant() {
  const [msgs, setMsgs] = useState([
    { role: "ai", text: "สวัสดีครับ J! 🧠 I'm your CHOWTO AI secretary. I know all your projects, tasks, and deals. Ask me anything — in Thai, Russian, or English.", ts: "now" },
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const endRef = useRef(null);

  useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [msgs]);

  const send = async () => {
    if (!input.trim() || loading) return;
    const text = input.trim();
    setInput("");
    setMsgs(p => [...p, { role: "user", text, ts: "now" }]);
    setLoading(true);

    const history = msgs.map(m => ({ role: m.role === "ai" ? "assistant" : "user", content: m.text }));
    history.push({ role: "user", content: text });

    const reply = await ai(text, `You are Booster_brain, AI secretary for J on Koh Samui, Thailand. J runs CHOWTO property management. Current context: ${TASKS.length} tasks (${TASKS.filter(t => t.priority === "urgent").length} urgent), ${PROJECTS.length} projects, ${CALENDAR_EVENTS.length} events today. Be concise, practical, speak Thai/Russian/English based on user. Current urgent: Follow up Russian client Dmitry about Chaweng Noi viewing.`);

    setMsgs(p => [...p, { role: "ai", text: reply, ts: "now" }]);
    setLoading(false);
  };

  const QUICK = ["📋 What are my urgent tasks?", "🏠 Status of Dmitry deal", "🔮 Analyze property market", "📅 What's on today?", "🌐 แปล: Follow up tomorrow", "⚡ Top 3 priorities now"];

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", padding: "24px 28px 16px" }} className="fade">
      <div style={{ marginBottom: 16 }}>
        <div style={{ color: C.text, fontSize: 22, fontFamily: "'Syne',sans-serif", fontWeight: 800 }}>AI Assistant</div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 4 }}>
          <div style={{ width: 7, height: 7, borderRadius: "50%", background: C.teal, animation: "blink 2s infinite" }} />
          <Mono c={C.teal} s={10}>Booster_brain online · TH 🇹🇭 RU 🇷🇺 EN 🇬🇧</Mono>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 14, paddingBottom: 14 }}>
        {msgs.map((m, i) => (
          <div key={i} style={{ display: "flex", justifyContent: m.role === "user" ? "flex-end" : "flex-start" }} className="fade">
            {m.role === "ai" && (
              <div style={{ width: 32, height: 32, borderRadius: "50%", background: C.goldD, border: `1px solid ${C.gold}44`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, flexShrink: 0, marginRight: 10 }}>🧠</div>
            )}
            <div style={{ maxWidth: "75%", padding: "11px 14px", borderRadius: m.role === "user" ? "14px 14px 2px 14px" : "14px 14px 14px 2px", background: m.role === "user" ? C.goldD : C.card, border: `1px solid ${m.role === "user" ? C.gold + "44" : C.border}`, color: C.text, fontSize: 13, lineHeight: 1.7 }}>
              {m.text}
            </div>
          </div>
        ))}
        {loading && (
          <div style={{ display: "flex", gap: 6, padding: "4px 8px" }}>
            <div style={{ width: 32, height: 32, borderRadius: "50%", background: C.goldD, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14 }}>🧠</div>
            <div style={{ display: "flex", gap: 4, alignItems: "center", background: C.card, padding: "10px 14px", borderRadius: 14, border: `1px solid ${C.border}` }}>
              {[0, 1, 2].map(i => <div key={i} style={{ width: 6, height: 6, borderRadius: "50%", background: C.gold, animation: `pulse 1s ${i * .2}s infinite` }} />)}
            </div>
          </div>
        )}
        <div ref={endRef} />
      </div>

      {/* Quick prompts */}
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 10 }}>
        {QUICK.map(q => (
          <button key={q} onClick={() => setInput(q)} style={{ padding: "5px 11px", borderRadius: 20, fontSize: 11, background: C.surface, border: `1px solid ${C.border}`, color: C.muted }}>
            {q}
          </button>
        ))}
      </div>

      <div style={{ display: "flex", gap: 8 }}>
        <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === "Enter" && send()} placeholder="Ask anything... Thai / Russian / English"
          style={{ flex: 1, background: C.card, border: `1px solid ${C.borderL}`, borderRadius: 10, color: C.text, padding: "11px 14px", fontSize: 13 }} />
        <button onClick={send} disabled={loading} style={{ padding: "11px 18px", borderRadius: 10, background: `linear-gradient(135deg, ${C.gold}, ${C.violet})`, color: "#fff", fontWeight: 700, fontSize: 14, opacity: loading ? .6 : 1 }}>↑</button>
      </div>
    </div>
  );
}

// ─── PROJECTS ─────────────────────────────────────────────────────────────────
function Projects() {
  return (
    <div style={{ padding: "24px 28px", display: "flex", flexDirection: "column", gap: 20, overflowY: "auto" }} className="fade">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ color: C.text, fontSize: 22, fontFamily: "'Syne',sans-serif", fontWeight: 800 }}>Projects</div>
        <button style={{ padding: "8px 16px", borderRadius: 8, background: C.gold, color: C.bg, fontSize: 13, fontWeight: 700 }}>+ New Project</button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {PROJECTS.map(p => (
          <div key={p.id} style={{ background: C.card, border: `1px solid ${p.risk ? C.red + "44" : C.border}`, borderRadius: 14, padding: 18, cursor: "pointer" }}
            onMouseEnter={e => e.currentTarget.style.borderColor = p.color + "66"}
            onMouseLeave={e => e.currentTarget.style.borderColor = p.risk ? C.red + "44" : C.border}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: p.color + "18", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20 }}>{p.icon}</div>
                <div>
                  <div style={{ color: C.text, fontSize: 14, fontWeight: 700 }}>{p.name}</div>
                  <Mono c={C.muted} s={10}>{p.tasks} tasks · {p.done} done</Mono>
                </div>
              </div>
              {p.risk && <Badge label="⚠️ risk" color={C.red} />}
            </div>
            <div style={{ height: 4, background: C.dim, borderRadius: 2, marginBottom: 10 }}>
              <div style={{ height: "100%", width: `${(p.done / p.tasks) * 100}%`, background: `linear-gradient(90deg, ${p.color}, ${p.color}88)`, borderRadius: 2 }} />
            </div>
            <div style={{ background: p.color + "0F", border: `1px solid ${p.color}22`, borderRadius: 8, padding: "8px 10px" }}>
              <Mono c={p.color} s={9}>🤖 AI INSIGHT</Mono>
              <div style={{ color: C.text, fontSize: 12, marginTop: 4, lineHeight: 1.5 }}>{p.insight}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── KNOWLEDGE BASE ───────────────────────────────────────────────────────────
function Knowledge() {
  const [search, setSearch] = useState("");
  const notes = [
    { title: "Dmitry negotiation terms", tags: ["Property Deals", "RU"], date: "Today", icon: "📝" },
    { title: "Thaledi lease agreement draft", tags: ["Thaledi", "Legal"], date: "Yesterday", icon: "📋" },
    { title: "Koh Samui market research Q2", tags: ["Research", "Finance"], date: "Apr 3", icon: "🔍" },
    { title: "Sarah — UK client requirements", tags: ["Property Deals", "EN"], date: "Apr 2", icon: "👤" },
    { title: "CHOWTO pricing strategy 2026", tags: ["Business", "Strategy"], date: "Apr 1", icon: "💡" },
  ];
  const filtered = search ? notes.filter(n => n.title.toLowerCase().includes(search.toLowerCase())) : notes;

  return (
    <div style={{ padding: "24px 28px", display: "flex", flexDirection: "column", gap: 18, overflowY: "auto" }} className="fade">
      <div style={{ color: C.text, fontSize: 22, fontFamily: "'Syne',sans-serif", fontWeight: 800 }}>Knowledge Base</div>
      <div style={{ position: "relative" }}>
        <Icon name="search" size={15} color={C.muted} style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)" }} />
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Smart search — tasks, notes, files, conversations..."
          style={{ width: "100%", background: C.card, border: `1px solid ${C.borderL}`, borderRadius: 10, color: C.text, padding: "11px 14px 11px 38px", fontSize: 13 }} />
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {filtered.map((n, i) => (
          <div key={i} style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 10, padding: "13px 15px", cursor: "pointer", display: "flex", gap: 12, alignItems: "center" }}
            onMouseEnter={e => e.currentTarget.style.borderColor = C.gold + "44"}
            onMouseLeave={e => e.currentTarget.style.borderColor = C.border}>
            <span style={{ fontSize: 20 }}>{n.icon}</span>
            <div style={{ flex: 1 }}>
              <div style={{ color: C.text, fontSize: 13, fontWeight: 500 }}>{n.title}</div>
              <div style={{ display: "flex", gap: 5, marginTop: 5 }}>
                {n.tags.map(t => <Tag key={t} label={t} color={C.blue} />)}
              </div>
            </div>
            <Mono c={C.muted} s={10}>{n.date}</Mono>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── RIGHT PANEL ──────────────────────────────────────────────────────────────
function RightPanel({ active }) {
  const now = new Date();
  const timeStr = now.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
  return (
    <div style={{ width: 280, borderLeft: `1px solid ${C.border}`, background: C.sidebar, display: "flex", flexDirection: "column", flexShrink: 0 }}>
      {/* Time */}
      <div style={{ padding: "20px 18px 14px", borderBottom: `1px solid ${C.border}` }}>
        <div style={{ color: C.text, fontSize: 28, fontFamily: "'Syne',sans-serif", fontWeight: 800 }}>{timeStr}</div>
        <Mono c={C.muted} s={10}>Koh Samui · GMT+7</Mono>
      </div>

      {/* Notifications */}
      <div style={{ padding: "14px 16px", borderBottom: `1px solid ${C.border}` }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
          <Mono c={C.muted} s={10}>NOTIFICATIONS</Mono>
          <Badge label="3" color={C.red} />
        </div>
        {[
          { icon: "🔥", text: "2 urgent tasks need action", color: C.red },
          { icon: "📅", text: "Meeting in 30 min", color: C.violet },
          { icon: "🏠", text: "Deal update required", color: C.gold },
        ].map((n, i) => (
          <div key={i} style={{ display: "flex", gap: 8, alignItems: "flex-start", marginBottom: 10, padding: "8px 10px", background: n.color + "0A", border: `1px solid ${n.color}22`, borderRadius: 8 }}>
            <span style={{ fontSize: 14 }}>{n.icon}</span>
            <div>
              <div style={{ color: C.text, fontSize: 11, lineHeight: 1.4 }}>{n.text}</div>
              <button style={{ color: n.color, fontSize: 10, marginTop: 3 }}>Take action →</button>
            </div>
          </div>
        ))}
      </div>

      {/* AI Suggestions */}
      <div style={{ padding: "14px 16px", flex: 1, overflowY: "auto" }}>
        <Mono c={C.violet} s={10}>🤖 AI NEXT ACTIONS</Mono>
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 10 }}>
          {[
            "Call Dmitry — no contact 2 days",
            "Upload Thaledi photos",
            "Review Sarah's contract",
            "Schedule Q2 financial review",
          ].map((s, i) => (
            <div key={i} style={{ display: "flex", gap: 8, alignItems: "flex-start", cursor: "pointer" }}>
              <div style={{ width: 20, height: 20, borderRadius: "50%", background: C.violetD, border: `1px solid ${C.violet}44`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 9, color: C.violet, flexShrink: 0 }}>{i + 1}</div>
              <span style={{ color: C.text, fontSize: 11, lineHeight: 1.5 }}>{s}</span>
            </div>
          ))}
        </div>

        {/* Quick add */}
        <div style={{ marginTop: 20, borderTop: `1px solid ${C.border}`, paddingTop: 14 }}>
          <Mono c={C.muted} s={10}>QUICK ADD</Mono>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginTop: 8 }}>
            {[["✅ Task", C.gold], ["🔔 Remind", C.violet], ["📅 Event", C.blue], ["📝 Note", C.teal]].map(([label, color]) => (
              <button key={label} style={{ padding: "8px 4px", borderRadius: 8, background: color + "12", border: `1px solid ${color}33`, color, fontSize: 11, fontWeight: 600 }}>{label}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── SEARCH BAR ───────────────────────────────────────────────────────────────
function TopBar({ active, setActive }) {
  const [search, setSearch] = useState("");
  return (
    <div style={{ height: 54, borderBottom: `1px solid ${C.border}`, display: "flex", alignItems: "center", padding: "0 24px", gap: 12, flexShrink: 0, background: C.bg }}>
      <div style={{ position: "relative", flex: 1, maxWidth: 440 }}>
        <Icon name="search" size={15} color={C.muted} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)" }} />
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search tasks, notes, files, conversations..."
          style={{ width: "100%", background: C.surface, border: `1px solid ${C.border}`, borderRadius: 8, color: C.text, padding: "8px 12px 8px 36px", fontSize: 13 }} />
      </div>
      <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" }}>
        <button onClick={() => setActive("ai")} style={{ display: "flex", alignItems: "center", gap: 6, padding: "6px 12px", borderRadius: 8, background: C.goldD, border: `1px solid ${C.gold}33`, color: C.gold, fontSize: 12, fontWeight: 600 }}>
          🧠 Ask Booster_brain
        </button>
        <div style={{ position: "relative" }}>
          <button style={{ width: 34, height: 34, borderRadius: 8, background: C.surface, border: `1px solid ${C.border}`, display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="bell" size={16} color={C.muted} />
          </button>
          <div style={{ position: "absolute", top: 6, right: 6, width: 8, height: 8, borderRadius: "50%", background: C.red, border: `2px solid ${C.bg}` }} />
        </div>
      </div>
    </div>
  );
}

// ─── APP ──────────────────────────────────────────────────────────────────────
function App() {
  const [active, setActive] = useState("dashboard");

  const pages = {
    dashboard: <Dashboard setActive={setActive} />,
    tasks:     <Tasks />,
    projects:  <Projects />,
    calendar:  <Calendar />,
    ai:        <AIAssistant />,
    knowledge: <Knowledge />,
  };

  return (
    <>
      <style>{css}</style>
      <div style={{ display: "flex", height: "100vh", overflow: "hidden", background: C.bg, color: C.text, fontFamily: "'DM Sans',sans-serif" }}>
        <Sidebar active={active} setActive={setActive} />
        <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
          <TopBar active={active} setActive={setActive} />
          <div style={{ flex: 1, overflow: "hidden" }}>
            {pages[active]}
          </div>
        </div>
        <RightPanel active={active} />
      </div>
    </>
  );
}
