/* Office Sidekick — Dashboard, widgets, command palette, customize UI */

const { useState: useStateW, useEffect: useEffectW, useRef: useRefW, useMemo: useMemoW, useCallback: useCallbackW } = React;

/* ============================================================
   GREETING helper
   ============================================================ */
function greeting(now) {
  const h = now.getHours();
  if (h < 5)  return { tag: "Late night",   line: "Burning the midnight oil." };
  if (h < 12) return { tag: "Good morning", line: "Welcome back. Let's get to it." };
  if (h < 14) return { tag: "Lunch hours",  line: "Quick win before the afternoon?" };
  if (h < 18) return { tag: "Afternoon",    line: "Second wind, second chance." };
  if (h < 22) return { tag: "Evening",      line: "Wrapping up — make it count." };
  return       { tag: "Late",                line: "Easy does it. One more thing, then rest." };
}

function formatNow(now) {
  return new Intl.DateTimeFormat([], { weekday: "long", month: "short", day: "numeric" }).format(now);
}
function formatTimeOnly(now, tz) {
  return new Intl.DateTimeFormat([], { timeZone: tz, hour: "2-digit", minute: "2-digit", hour12: false }).format(now);
}

/* ============================================================
   DASHBOARD
   ============================================================ */
function Dashboard() {
  const app = window.Office.useApp();
  const { now, pomo, startPomo, pausePomo, setRoute, pinned, customizing } = app;
  const g = greeting(now);
  const remaining = pomo.remainingMs;
  const pomoPct = pomo.totalMs ? (1 - remaining / pomo.totalMs) * 100 : 0;
  const focusState = pomo.running
    ? (pomo.mode === "focus" ? "Focus block · running" : pomo.mode === "short" ? "Short break · running" : "Long break · running")
    : (remaining < pomo.totalMs ? "Paused — pick it up" : "Ready when you are");

  const wdStart = 9, wdEnd = 17;
  const hrs = now.getHours() + now.getMinutes() / 60;
  const dayPct = Math.max(0, Math.min(100, ((hrs - wdStart) / (wdEnd - wdStart)) * 100));
  const dayLabel = hrs < wdStart ? "Before hours"
                 : hrs > wdEnd   ? "After hours"
                 : "Workday";
  const remainingHrs = Math.max(0, wdEnd - hrs);
  const remainingHrsLabel = remainingHrs >= 1
    ? `${Math.floor(remainingHrs)}h ${Math.round((remainingHrs % 1) * 60)}m left`
    : `${Math.round(remainingHrs * 60)}m left`;

  return (
    <div>
      {/* Hero row */}
      <div className="dash-hero">
        <div className="greet">
          <div className="greet-tag">
            <span className="pulse"></span>
            <span>{g.tag} · {formatNow(now)}</span>
          </div>
          <h1>{g.line} <em>{firstName()}.</em></h1>
          <div className="greet-meta">
            <span>🕐 <b>{formatTimeOnly(now)}</b> local</span>
            <span>📌 <b>{pinned.length}</b> widget{pinned.length === 1 ? "" : "s"} pinned</span>
            <span>🔄 <b>{pomo.running ? "Pomodoro running" : "Ready to focus"}</b></span>
          </div>
          <div className="greet-cta">
            {pomo.running ? (
              <button className="btn btn-primary" onClick={() => setRoute("pomodoro")}>
                ⏱  Open timer ({window.Office.fmtMs(pomo.remainingMs)})
              </button>
            ) : (
              <button className="btn btn-primary" onClick={() => { startPomo("focus"); setRoute("focus-mode"); }}>
                ▶  Start a focus block
              </button>
            )}
            <button className="btn btn-ghost" onClick={() => setRoute("watercooler")}>
              ☕  Watercooler
            </button>
            <button className="btn btn-ghost" onClick={() => app.setCmdOpen(true)}>
              ⌘K  Search tools
            </button>
          </div>
        </div>

        <div className="focus-card">
          <div className="row">
            <h3>Focus Session</h3>
            <div className="spacer"></div>
            <span className="focus-state">{focusState}</span>
          </div>
          <div className="focus-time">{window.Office.fmtMs(pomo.remainingMs)}</div>
          <div className="focus-ring">
            <div className="focus-ring-fill" style={{ width: pomoPct + "%" }}></div>
          </div>
          <div className="row" style={{ justifyContent: "space-between", fontSize: 12, color: "var(--vps-text-muted)" }}>
            <span className="mono">
              {pomo.mode === "focus" ? `Session ${pomo.sessionIdx} of ${pomo.cycles}` : pomo.mode === "short" ? "Short break" : "Long break"}
            </span>
            <span className="mono">{Math.round(pomoPct)}%</span>
          </div>
          <div className="focus-actions">
            {pomo.running ? (
              <button className="btn btn-danger btn-sm" onClick={pausePomo}>⏸ Pause</button>
            ) : (
              <button className="btn btn-amber btn-sm" onClick={() => startPomo()}>▶ Start</button>
            )}
            <button className="btn btn-ghost btn-sm" onClick={() => setRoute("pomodoro")}>Open Pomodoro →</button>
          </div>
        </div>
      </div>

      {/* Customize bar */}
      <CustomizeBar />

      {/* Pinned widgets */}
      <PinnedWidgets
        hrs={hrs}
        dayPct={dayPct}
        dayLabel={dayLabel}
        remainingHrsLabel={remainingHrsLabel}
        now={now}
      />

      {/* Tool grid */}
      <ToolSections />
    </div>
  );
}

function firstName() {
  return "there";
}

/* ============================================================
   CUSTOMIZE BAR
   ============================================================ */
function CustomizeBar() {
  const app = window.Office.useApp();
  const { customizing, setCustomizing, setAddOpen, pinned } = app;

  return (
    <div className={"customize-bar " + (customizing ? "active" : "")}>
      <div className="cb-left">
        <span className="cb-title">
          {customizing ? "Customizing dashboard" : "Your dashboard"}
        </span>
        <span className="cb-sub">
          {customizing
            ? "Click − to remove a widget, or use Add widget to pin more tools."
            : `${pinned.length} pinned · click any tool below to pin it, or hit Customize.`}
        </span>
      </div>
      <div className="cb-actions">
        <button className="btn btn-ghost btn-sm" onClick={() => setAddOpen(true)}>
          ＋ Add widget
        </button>
        <button
          className={"btn btn-sm " + (customizing ? "btn-primary" : "btn-ghost")}
          onClick={() => setCustomizing(c => !c)}
        >
          {customizing ? "✓ Done" : "⚙ Customize"}
        </button>
      </div>
    </div>
  );
}

/* ============================================================
   PINNED WIDGETS row
   ============================================================ */
function PinnedWidgets({ hrs, dayPct, dayLabel, remainingHrsLabel, now }) {
  const app = window.Office.useApp();
  const { pinned, customizing, togglePin, setRoute, setAddOpen } = app;
  const { TOOL_BY_ID } = window.Office;

  const compactRegistry = window.CompactWidgets || {};

  return (
    <div className="widget-row">
      {/* Workday is always present (it's not a tool) */}
      <DayProgressWidget hrs={hrs} dayPct={dayPct} dayLabel={dayLabel} remainingHrsLabel={remainingHrsLabel} now={now} />

      {pinned.map(id => {
        const tool = TOOL_BY_ID[id];
        if (!tool) return null;
        const Compact = tool.compact ? compactRegistry[id] : null;
        return (
          <div className={"widget pinned-widget " + (customizing ? "shake" : "")} key={id}>
            <div className="w-head">
              <div className="w-head-left">
                <span className="w-icon" aria-hidden="true">{tool.icon}</span>
                <span className="w-title">{tool.name}</span>
              </div>
              {customizing && (
                <button className="w-remove" title="Remove from dashboard" onClick={() => togglePin(id)}>−</button>
              )}
              {!customizing && (
                <button className="w-open" title={"Open " + tool.name} onClick={() => setRoute(id)}>↗</button>
              )}
            </div>
            <div className="w-body">
              {Compact ? <Compact /> : (
                <div className="w-launcher">
                  <p>{tool.desc}</p>
                  <button className="btn btn-ghost btn-sm" onClick={() => setRoute(id)}>
                    Open {tool.name} →
                  </button>
                </div>
              )}
            </div>
          </div>
        );
      })}

      {/* Add widget tile */}
      <button className="widget add-widget" onClick={() => setAddOpen(true)}>
        <div className="add-widget-plus">＋</div>
        <div>
          <div className="add-widget-title">Add a widget</div>
          <div className="add-widget-sub">Pin any tool to your dashboard</div>
        </div>
      </button>
    </div>
  );
}

/* ============================================================
   DAY PROGRESS (always present, not a removable widget)
   ============================================================ */
function DayProgressWidget({ hrs, dayPct, dayLabel, remainingHrsLabel, now }) {
  return (
    <div className="widget" style={{ cursor: "default" }}>
      <div className="w-head">
        <div className="w-head-left">
          <span className="w-icon" aria-hidden="true">📅</span>
          <span className="w-title">Workday</span>
        </div>
        <span className="mono" style={{ fontSize: 11, color: "var(--vps-text-muted)" }}>
          9 — 17
        </span>
      </div>
      <div className="daybar-big">{Math.round(dayPct)}<span style={{ fontSize: 18, color: "var(--vps-text-muted)" }}>%</span></div>
      <div className="daybar-sub">{dayLabel} · {remainingHrsLabel}</div>
      <div className="daybar-track">
        <div className="daybar-fill" style={{ width: Math.max(0, Math.min(100, dayPct)) + "%" }}></div>
        <div className="daybar-marks">
          {Array.from({ length: 9 }).map((_, i) => <span key={i}></span>)}
        </div>
      </div>
      <div className="daybar-meta">
        <span>9:00</span>
        <span><b>{formatTimeOnly(now)}</b></span>
        <span>17:00</span>
      </div>
    </div>
  );
}

/* ============================================================
   TOOL SECTIONS (grouped by category)
   ============================================================ */
function ToolSections() {
  const app = window.Office.useApp();
  const { TOOLS, CATEGORIES, TOOL_BY_ID } = window.Office;

  return (
    <div style={{ marginTop: 16 }}>
      {/* Recently used */}
      {app.recent.length > 0 && (
        <div style={{ marginBottom: 28 }}>
          <div className="section-head">
            <h2>Recent <span className="count">· {app.recent.length}</span></h2>
            <span className="head-line">Jump back in</span>
          </div>
          <div className="tool-grid">
            {app.recent.map(id => {
              const t = TOOL_BY_ID[id];
              if (!t) return null;
              return <ToolTile key={id} tool={t} />;
            })}
          </div>
        </div>
      )}

      {CATEGORIES.map(cat => {
        const list = TOOLS.filter(t => t.cat === cat.id);
        if (list.length === 0) return null;
        return (
          <div key={cat.id} style={{ marginBottom: 28 }}>
            <div className="section-head">
              <h2>{cat.label} <span className="count">· {list.length}</span></h2>
              <span className="head-line">{categoryLine(cat.id)}</span>
            </div>
            <div className="tool-grid">
              {list.map(t => <ToolTile key={t.id} tool={t} />)}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function categoryLine(id) {
  switch (id) {
    case "focus":    return "Get heads-down quickly";
    case "break":    return "A 90-second mental reset";
    case "write":    return "Move thoughts to text";
    case "live":     return "Public APIs, no key needed";
    case "meetings": return "Make calls less painful";
    case "utility":  return "Boring problems, solved";
    default: return "";
  }
}

function ToolTile({ tool }) {
  const app = window.Office.useApp();
  const isLive = tool.id === "pomodoro" && app.pomo.running;
  const pinned = app.isPinned(tool.id);
  return (
    <div className={"tile " + (tool.color || "") + (pinned ? " is-pinned" : "")}>
      <button className="tile-body" onClick={() => app.setRoute(tool.id)}>
        <div className="tile-icon">{tool.icon}</div>
        <h3>{tool.name}</h3>
        <p>{tool.desc}</p>
        {tool.isNew && <span className="tile-tag new">New</span>}
        {isLive && <span className="tile-tag">{window.Office.fmtMs(app.pomo.remainingMs)}</span>}
      </button>
      <button
        className={"tile-pin " + (pinned ? "pinned" : "")}
        title={pinned ? "Pinned — click to remove from dashboard" : "Pin to dashboard"}
        onClick={(e) => { e.stopPropagation(); app.togglePin(tool.id); }}
      >
        {pinned ? "✓ Pinned" : "+ Pin"}
      </button>
    </div>
  );
}

/* ============================================================
   ADD WIDGET PICKER (modal)
   ============================================================ */
function AddWidgetPicker({ onClose }) {
  const app = window.Office.useApp();
  const { TOOLS, CATEGORIES } = window.Office;
  const [q, setQ] = useStateW("");

  const filtered = useMemoW(() => {
    const ql = q.trim().toLowerCase();
    if (!ql) return TOOLS;
    return TOOLS.filter(t =>
      t.name.toLowerCase().includes(ql) ||
      (t.desc || "").toLowerCase().includes(ql) ||
      (t.kw || "").toLowerCase().includes(ql)
    );
  }, [q]);

  return (
    <div className="cmd-overlay" onClick={onClose}>
      <div className="add-modal" onClick={e => e.stopPropagation()}>
        <div className="add-modal-head">
          <div>
            <h3>Add a widget</h3>
            <p>Pin any tool to your dashboard. {app.pinned.length} of {TOOLS.length} pinned.</p>
          </div>
          <button className="icon-btn" onClick={onClose} title="Close">✕</button>
        </div>
        <input
          className="cmd-input"
          autoFocus
          placeholder="Filter tools…"
          value={q}
          onChange={e => setQ(e.target.value)}
        />
        <div className="add-modal-body">
          {CATEGORIES.map(cat => {
            const list = filtered.filter(t => t.cat === cat.id);
            if (list.length === 0) return null;
            return (
              <div key={cat.id} className="add-cat">
                <h4>{cat.label}</h4>
                <div className="add-cat-grid">
                  {list.map(tool => {
                    const pinned = app.isPinned(tool.id);
                    return (
                      <button
                        key={tool.id}
                        className={"add-card " + (pinned ? "pinned" : "")}
                        onClick={() => app.togglePin(tool.id)}
                      >
                        <div className="add-card-ic">{tool.icon}</div>
                        <div className="add-card-text">
                          <div className="add-card-name">
                            {tool.name}
                            {tool.compact && <span className="add-card-pill">live widget</span>}
                            {tool.isNew && <span className="add-card-pill new">new</span>}
                          </div>
                          <div className="add-card-desc">{tool.desc}</div>
                        </div>
                        <div className={"add-card-toggle " + (pinned ? "on" : "")}>
                          {pinned ? "✓ Pinned" : "+ Pin"}
                        </div>
                      </button>
                    );
                  })}
                </div>
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div className="muted" style={{ padding: 20, textAlign: "center" }}>
              No tools match "{q}".
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   COMMAND PALETTE
   ============================================================ */
function CommandPalette({ onClose }) {
  const app = window.Office.useApp();
  const [q, setQ] = useStateW("");
  const [idx, setIdx] = useStateW(0);
  const inputRef = useRefW(null);

  useEffectW(() => { inputRef.current?.focus(); }, []);

  const results = useMemoW(() => {
    const ql = q.trim().toLowerCase();
    const items = [
      { type: "tool", id: "dashboard", name: "Dashboard", desc: "Overview", icon: "⌂", kw: "home overview" },
      ...window.Office.TOOLS.map(t => ({ type: "tool", id: t.id, name: t.name, desc: t.desc, icon: t.icon, kw: t.kw || "" })),
      { type: "tool", id: "about", name: "About", desc: "How this works", icon: "🛡️", kw: "security privacy" },
      { type: "action", id: "act-pomo", name: app.pomo.running ? "Pause pomodoro" : "Start a focus block", desc: "Quick action", icon: "▶", run: () => { app.pomo.running ? app.pausePomo() : app.startPomo("focus"); } },
      { type: "action", id: "act-reset", name: "Reset pomodoro", desc: "Quick action", icon: "↺", run: () => app.resetPomo() },
      { type: "action", id: "act-scratch", name: "Open scratchpad", desc: "Quick action", icon: "🗒️", run: () => app.setRoute("scratchpad") },
      { type: "action", id: "act-customize", name: app.customizing ? "Stop customizing dashboard" : "Customize dashboard", desc: "Quick action", icon: "⚙", run: () => { app.setRoute("dashboard"); app.setCustomizing(c => !c); } },
      { type: "action", id: "act-add", name: "Add a widget to dashboard", desc: "Quick action", icon: "＋", run: () => { app.setRoute("dashboard"); app.setAddOpen(true); } },
    ];
    if (!ql) return items;
    return items.filter(it =>
      it.name.toLowerCase().includes(ql) ||
      (it.desc || "").toLowerCase().includes(ql) ||
      (it.kw || "").toLowerCase().includes(ql)
    );
  }, [q, app.pomo.running, app.customizing]);

  useEffectW(() => { setIdx(0); }, [q]);

  const choose = (item) => {
    if (item.type === "action") { item.run?.(); }
    else { app.setRoute(item.id); }
    onClose();
  };

  const onKey = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setIdx(i => Math.min(i + 1, results.length - 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setIdx(i => Math.max(i - 1, 0)); }
    else if (e.key === "Enter") { e.preventDefault(); results[idx] && choose(results[idx]); }
  };

  return (
    <div className="cmd-overlay" onClick={onClose}>
      <div className="cmd" onClick={e => e.stopPropagation()}>
        <input
          ref={inputRef}
          className="cmd-input"
          placeholder="Search tools, jump anywhere…"
          value={q}
          onChange={e => setQ(e.target.value)}
          onKeyDown={onKey}
        />
        <div className="cmd-list">
          {results.length === 0 && <div className="cmd-item" style={{ color: "var(--vps-text-muted)" }}>No matches</div>}
          {results.filter(r => r.type === "tool").length > 0 && <div className="cmd-section-title">Tools</div>}
          {results.filter(r => r.type === "tool").map((r) => {
            const realIdx = results.indexOf(r);
            return (
              <div
                key={r.id}
                className={"cmd-item " + (realIdx === idx ? "active" : "")}
                onClick={() => choose(r)}
                onMouseEnter={() => setIdx(realIdx)}
              >
                <span className="ic">{r.icon}</span>
                <span>{r.name}</span>
                <span className="desc">{r.desc}</span>
              </div>
            );
          })}
          {results.filter(r => r.type === "action").length > 0 && <div className="cmd-section-title">Actions</div>}
          {results.filter(r => r.type === "action").map((r) => {
            const realIdx = results.indexOf(r);
            return (
              <div
                key={r.id}
                className={"cmd-item " + (realIdx === idx ? "active" : "")}
                onClick={() => choose(r)}
                onMouseEnter={() => setIdx(realIdx)}
              >
                <span className="ic">{r.icon}</span>
                <span>{r.name}</span>
                <span className="desc">{r.desc}</span>
              </div>
            );
          })}
        </div>
        <div className="cmd-foot">
          <span><span className="kbd">↑↓</span>navigate</span>
          <span><span className="kbd">⏎</span>open</span>
          <span><span className="kbd">esc</span>close</span>
        </div>
      </div>
    </div>
  );
}

/* Expose to global scope */
window.Dashboard = Dashboard;
window.AboutView = AboutView;
window.CommandPalette = CommandPalette;
window.AddWidgetPicker = AddWidgetPicker;
