// Shared UI bits + icons
const { useState, useEffect, useMemo, useRef } = React;

const Icon = {
  Home: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/><path d="M10 21v-6h4v6"/>
    </svg>
  ),
  Box: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3.3 7.5 12 12l8.7-4.5"/><path d="M12 22V12"/><path d="M21 7.5v9L12 22 3 16.5v-9L12 3z"/>
    </svg>
  ),
  Doc: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6"/><path d="M8 13h8"/><path d="M8 17h5"/>
    </svg>
  ),
  Users: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M17 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9.5" cy="7" r="3.5"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
    </svg>
  ),
  Calendar: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="16" rx="1.5"/><path d="M3 9.5h18"/><path d="M8 3v4"/><path d="M16 3v4"/>
    </svg>
  ),
  Bell: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 8a6 6 0 1 1 12 0c0 6 3 7 3 7H3s3-1 3-7"/><path d="M10.5 19a1.5 1.5 0 0 0 3 0"/>
    </svg>
  ),
  Cog: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3h0a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5h0a1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8v0a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/>
    </svg>
  ),
  Search: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/>
    </svg>
  ),
  Plus: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 5v14M5 12h14"/>
    </svg>
  ),
  Chev: ({ dir = "left" }) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ transform: dir === "right" ? "rotate(180deg)" : "none" }}>
      <path d="m15 6-6 6 6 6"/>
    </svg>
  ),
  Filter: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 5h18l-7 9v6l-4-2v-4z"/>
    </svg>
  ),
  Download: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/>
    </svg>
  ),
  Plane: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M17.8 19.7 13 14.9V9.5l8-4.5V3l-9 3.5L3 4v2.5l5.5 3v5.5l-3.5 2v1.5l4.5-1 3.5 3z"/>
    </svg>
  ),
  Refresh: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12a9 9 0 1 1-3.2-6.9"/><path d="M21 4v5h-5"/>
    </svg>
  ),
  Dot: () => (
    <svg viewBox="0 0 6 6"><circle cx="3" cy="3" r="3" fill="currentColor"/></svg>
  ),
  Info: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9"/><path d="M12 16v-5"/><circle cx="12" cy="8" r=".5" fill="currentColor"/>
    </svg>
  ),
};

// ---------- Sidebar ----------
function Sidebar({ active = "home" }) {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    document.body.classList.toggle("nav-open", open);
    return () => document.body.classList.remove("nav-open");
  }, [open]);

  const item = (key, label, icon, badge) => (
    <a className={`nav-item ${active === key ? "active" : ""}`}
       onClick={() => setOpen(false)}
       href={key === "home" ? "/" : key === "parts" ? "/parts.html" : key === "req" ? "/requests.html" : key === "clients" ? "/clients.html" : "#"}>
      {icon} {label}
      {badge && <span className="badge-inline">{badge}</span>}
    </a>
  );
  return (
    <React.Fragment>
      <button
        className="hamburger"
        aria-label={open ? "Close menu" : "Open menu"}
        aria-expanded={open}
        onClick={() => setOpen(o => !o)}
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
          {open
            ? <g><path d="M6 6l12 12"/><path d="M18 6L6 18"/></g>
            : <g><path d="M4 7h16"/><path d="M4 12h16"/><path d="M4 17h16"/></g>}
        </svg>
      </button>
      <div className={`sidebar-backdrop ${open ? "open" : ""}`} onClick={() => setOpen(false)}></div>
      <aside className={`sidebar ${open ? "open" : ""}`}>
        <div className="brand">
          <img src="nexus-logo.png" alt="Nexus Rostov" className="brand-logo"/>
        </div>

        <div className="nav-section">Workspace</div>
        <nav className="nav">
          {item("home",   "Home",     <Icon.Home/>)}
          {item("parts",  "Parts",    <Icon.Box/>,    "21")}
          {item("req",    "Requests", <Icon.Doc/>,    "5")}
          {item("clients","Clients",  <Icon.Users/>)}
          {item("cal",    "Calendar", <Icon.Calendar/>)}
        </nav>

        <div className="nav-section">Inbox</div>
        <nav className="nav">
          {item("notif",   "Notifications", <Icon.Bell/>, "2")}
          {item("settings","Settings",      <Icon.Cog/>)}
        </nav>

        <div className="side-foot">
          <div className="user-chip">
            <div className="avatar">JD</div>
            <div>
              <div className="name">John Doe</div>
              <div className="email">john@nexusaero.io</div>
            </div>
          </div>
        </div>
      </aside>
    </React.Fragment>
  );
}

// ---------- Sync widget (WhatsApp basket pusher) ----------
// Live during business window (default 9–5 PST Mon–Fri); outside, pushes a
// digest at the configured digest time. Settings live in window.__SYNC_CFG
// and can be adjusted via the popover.

const DEFAULT_SYNC_CFG = {
  channel: "whatsapp",
  interval: 3,          // minutes
  windowStart: "09:00", // PST
  windowEnd: "17:00",
  tz: "PST",
  digestTime: "09:00",
  days: ["Mon", "Tue", "Wed", "Thu", "Fri"],
};

function SyncWidget({ mode }) {
  const [now, setNow] = useState(() => new Date("2026-05-20T14:32:18-07:00"));
  const [open, setOpen] = useState(false);
  const [cfg, setCfg] = useState(() => {
    try { return { ...DEFAULT_SYNC_CFG, ...(JSON.parse(localStorage.getItem("nx-sync") || "{}")) }; }
    catch { return DEFAULT_SYNC_CFG; }
  });
  const updateCfg = (patch) => {
    const next = { ...cfg, ...patch };
    setCfg(next);
    try { localStorage.setItem("nx-sync", JSON.stringify(next)); } catch {}
  };
  const popRef = useRef(null);

  useEffect(() => {
    const id = setInterval(() => setNow(n => new Date(n.getTime() + 1000)), 1000);
    return () => clearInterval(id);
  }, []);

  useEffect(() => {
    if (!open) return;
    const onClick = (e) => {
      if (popRef.current && !popRef.current.contains(e.target)) setOpen(false);
    };
    window.addEventListener("mousedown", onClick);
    return () => window.removeEventListener("mousedown", onClick);
  }, [open]);

  // Anchored PST snapshot for the prototype's "now"
  const pstHour = 14;
  const pstDow  = 3; // Wed
  const isBiz   = pstDow >= 1 && pstDow <= 5
                && pstHour >= parseInt(cfg.windowStart) && pstHour < parseInt(cfg.windowEnd);
  const effectiveLive = mode === "auto" ? isBiz : mode === "live";

  // Countdown to next interval-minute boundary
  const sec = now.getSeconds();
  const min = now.getMinutes();
  const iv = Math.max(1, cfg.interval);
  const nextMin = Math.ceil((min + 1) / iv) * iv;
  const overflow = nextMin >= 60;
  const remainSec = (overflow ? 60 - min : nextMin - min) * 60 - sec;
  const mm = String(Math.floor(remainSec / 60)).padStart(2, "0");
  const ss = String(remainSec % 60).padStart(2, "0");

  const channelLabel = { whatsapp: "WhatsApp", sms: "SMS", email: "Email" }[cfg.channel] || "WhatsApp";

  return (
    <div style={{ position: "relative" }}>
      <button className={`sync-widget ${effectiveLive ? "is-live" : "is-off"}`} onClick={() => setOpen(o => !o)}>
        <span className={`sync-status ${effectiveLive ? "live" : "off"}`}>
          <span className="ping"></span>
          <span className="sync-label">
            {effectiveLive ? `Pushing · ${channelLabel} · ${iv}m basket` : `Off-hours · ${channelLabel} digest`}
          </span>
        </span>
        <span className="sync-sep"></span>
        <span className="sync-meta">
          <span>{effectiveLive ? "Next push" : "Next digest"}</span>
          <span className="mono">{effectiveLive ? `${mm}:${ss}` : `${cfg.digestTime} ${cfg.tz}`}</span>
        </span>
        <span className="sync-caret"><Icon.Chev dir="right"/></span>
      </button>

      {open && (
        <div className="sync-pop" ref={popRef}>
          <div className="pop-head">
            <div>
              <div className="pop-title">Push settings</div>
              <div className="pop-sub">Basket cadence + window for {channelLabel} notifications</div>
            </div>
            <button className="x" onClick={() => setOpen(false)} aria-label="Close">×</button>
          </div>

          <div className="pop-field">
            <div className="pop-label">Channel</div>
            <div className="seg-group">
              {[
                { v: "whatsapp", l: "WhatsApp" },
                { v: "sms", l: "SMS" },
                { v: "email", l: "Email" },
              ].map(o => (
                <button key={o.v}
                        className={`seg ${cfg.channel === o.v ? "active" : ""}`}
                        onClick={() => updateCfg({ channel: o.v })}>{o.l}</button>
              ))}
            </div>
          </div>

          <div className="pop-field">
            <div className="pop-label">Basket interval <span className="pop-hint">while in window</span></div>
            <div className="seg-group">
              {[1, 3, 5, 10, 15].map(v => (
                <button key={v}
                        className={`seg ${cfg.interval === v ? "active" : ""}`}
                        onClick={() => updateCfg({ interval: v })}>{v}m</button>
              ))}
            </div>
          </div>

          <div className="pop-field">
            <div className="pop-label">Business hours window</div>
            <div className="time-row">
              <input className="time-in mono" type="time" value={cfg.windowStart}
                     onChange={(e) => updateCfg({ windowStart: e.target.value })}/>
              <span className="dash">→</span>
              <input className="time-in mono" type="time" value={cfg.windowEnd}
                     onChange={(e) => updateCfg({ windowEnd: e.target.value })}/>
              <select className="time-in mono" value={cfg.tz}
                      onChange={(e) => updateCfg({ tz: e.target.value })}>
                <option>PST</option><option>EST</option><option>UTC</option><option>CET</option>
              </select>
            </div>
          </div>

          <div className="pop-field">
            <div className="pop-label">Days</div>
            <div className="day-row">
              {["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(d => {
                const on = cfg.days.includes(d);
                return (
                  <button key={d}
                          className={`day ${on ? "active" : ""}`}
                          onClick={() => updateCfg({ days: on ? cfg.days.filter(x => x !== d) : [...cfg.days, d] })}>{d}</button>
                );
              })}
            </div>
          </div>

          <div className="pop-field">
            <div className="pop-label">Off-hours digest sent at</div>
            <input className="time-in mono" type="time" value={cfg.digestTime}
                   onChange={(e) => updateCfg({ digestTime: e.target.value })}
                   style={{ width: 120 }}/>
          </div>

          <div className="pop-foot">
            <span className="mono">12 recipients · 3 baskets last hour</span>
            <a className="pop-link" href="#">Manage recipients →</a>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- Topbar ----------
function Topbar({ syncMode, heading }) {
  return (
    <header className="topbar">
      {heading || (
        <div className="page-heading">
          <span className="page-heading-day">Wednesday, May 20</span>
          <span className="page-heading-year">2026</span>
        </div>
      )}
      <div className="search">
        <Icon.Search/>
        <input placeholder="Search NX number, part, client, or request…" />
        <kbd>⌘K</kbd>
      </div>
      <div className="spacer"></div>
      <SyncWidget mode={syncMode}/>
      <div className="topbar-actions">
        <button className="btn"><Icon.Plane/> New request</button>
        <button className="btn primary"><Icon.Plus/> Add part</button>
        <button className="icon-btn" title="Refresh"><Icon.Refresh/></button>
        <button className="icon-btn" title="Notifications">
          <Icon.Bell/>
          <span className="dot-badge">2</span>
        </button>
      </div>
    </header>
  );
}

Object.assign(window, { Icon, Sidebar, SyncWidget, Topbar });
