// Shared chrome: LeftNav, TopNav, StatusBadge, Sparkline, Icon helper.
(function () {

const { useState } = React;
const { font, fg, muted, border, cardBg } = window.MAX_DATA;

// Lucide icons available on window.lucide.icons (lucide UMD exposes them lazily).
// We'll use lucide.createElement-like approach by reading icon component from `lucide` global.
function Icon({ name, size = 16, color = "currentColor", strokeWidth = 2, style }) {
  // Render via a span that uses inline SVG path lookup? Easier: use the iconNode from lucide and render manually.
  const lucide = window.lucide;
  const node = lucide && lucide.icons && lucide.icons[name];
  if (!node) {
    return <span style={{ display: "inline-block", width: size, height: size, ...style }} />;
  }
  // node = ['svg', attrs, [['path', {...}], ...]]
  const [tag, baseAttrs, children] = node;
  const attrs = {
    ...baseAttrs,
    width: size,
    height: size,
    stroke: color,
    strokeWidth,
    style,
  };
  return (
    <svg {...attrs} xmlns="http://www.w3.org/2000/svg">
      {children.map((c, i) => {
        const [ctag, cattrs] = c;
        return React.createElement(ctag, { key: i, ...cattrs });
      })}
    </svg>
  );
}

const statusColors = {
  active: { bg: "#dcfce7", text: "#166534", dot: "#22c55e" },
  pilot: { bg: "#dbeafe", text: "#1e40af", dot: "#3b82f6" },
  building: { bg: "#fef3c7", text: "#92400e", dot: "#f59e0b" },
  planned: { bg: "#f3f4f6", text: "#4b5563", dot: "#9ca3af" },
};

function StatusBadge({ status }) {
  const s = statusColors[status];
  return (
    <span style={{ background: s.bg, color: s.text, fontSize: 10, fontWeight: 700, padding: "2px 8px", borderRadius: 99, display: "inline-flex", alignItems: "center", gap: 4, textTransform: "capitalize", letterSpacing: 0.3, fontFamily: font }}>
      <span style={{ width: 5, height: 5, borderRadius: 99, background: s.dot }} />
      {status}
    </span>
  );
}

function Sparkline({ data, color = "#2563eb" }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const points = data.map((v, i) => `${(i / (data.length - 1)) * 50},${16 - ((v - min) / range) * 16}`).join(" ");
  return (
    <svg width="50" height="16" style={{ display: "inline-block" }}>
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" />
    </svg>
  );
}

function LeftNav({ activePage, setActivePage }) {
  const [maxExpanded, setMaxExpanded] = useState(true);
  const maxPages = ["max-home", "automations", "journeys"];
  const isMaxActive = maxPages.includes(activePage);
  const maxSub = [
    { id: "max-home", label: "Max" },
    { id: "automations", label: "Automations" },
    { id: "journeys", label: "Journeys" },
  ];
  const otherNav = [
    { label: "Calls", icon: "Phone" },
    { label: "Schedule", icon: "Calendar" },
    { label: "Dispatch", icon: "Truck" },
    { label: "Accounting", icon: "Clipboard" },
    { label: "Inventory", icon: "Box" },
    { label: "Follow Up", icon: "Flag" },
    { label: "Reports", icon: "FileBarChart" },
    { label: "Marketing", icon: "Megaphone" },
    { label: "Pricebook", icon: "BookOpen" },
  ];

  const NavBtn = ({ icon, label, active, onClick, opacity }) => (
    <button onClick={onClick} style={{ width: "100%", padding: "10px 0", display: "flex", flexDirection: "column", alignItems: "center", gap: 3, background: "none", border: "none", cursor: "pointer", borderLeft: active ? "2px solid #78bbfa" : "2px solid transparent", opacity: opacity || 1 }}>
      <Icon name={icon} size={18} color={active ? "#78bbfa" : "white"} strokeWidth={1.5} />
      <span style={{ fontSize: 9, color: active ? "#78bbfa" : "white", fontFamily: font, fontWeight: 600 }}>{label}</span>
    </button>
  );

  return (
    <div style={{ width: 70, background: "#141414", display: "flex", flexDirection: "column", alignItems: "center", paddingTop: 10, gap: 0, flexShrink: 0, overflowY: "auto" }}>
      <NavBtn icon="Compass" label="Dashboard" opacity={0.5} onClick={() => {}} />
      <NavBtn icon="TrendingUp" label="Max" active={isMaxActive} onClick={() => { setMaxExpanded(!maxExpanded); if (!isMaxActive) setActivePage("max-home"); }} />
      {maxExpanded && (
        <div style={{ width: "100%", background: "rgba(255,255,255,0.05)", padding: "4px 0" }}>
          {maxSub.map(s => (
            <button key={s.id} onClick={() => setActivePage(s.id)} style={{ width: "100%", padding: "7px 4px", background: activePage === s.id ? "rgba(120,187,250,0.15)" : "transparent", border: "none", cursor: "pointer" }}>
              <span style={{ fontSize: 9, color: activePage === s.id ? "#78bbfa" : "rgba(255,255,255,0.55)", fontFamily: font, fontWeight: 600, display: "block", textAlign: "center" }}>{s.label}</span>
            </button>
          ))}
        </div>
      )}
      <div style={{ width: 36, height: 1, background: "rgba(255,255,255,0.1)", margin: "6px 0" }} />
      {otherNav.map(n => <NavBtn key={n.label} icon={n.icon} label={n.label} opacity={0.45} onClick={() => {}} />)}
    </div>
  );
}

function TopNav() {
  return (
    <div style={{ height: 48, background: cardBg, borderBottom: `1px solid ${border}`, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 16px", flexShrink: 0 }}>
      <span style={{ fontSize: 15, fontWeight: 800, fontFamily: font, color: fg, letterSpacing: -0.5 }}>ServiceTitan</span>
      <div style={{ display: "flex", alignItems: "center", background: cardBg, border: "1px solid #c4c5c6", borderRadius: 10, padding: "4px 12px", gap: 8, width: 300 }}>
        <Icon name="Search" size={15} color="#999" />
        <span style={{ fontSize: 12, color: "#999", fontFamily: font }}>Search</span>
        <span style={{ marginLeft: "auto", fontSize: 10, color: "#aaa", background: "#eee", padding: "1px 6px", borderRadius: 4, fontFamily: font }}>CTRL + /</span>
      </div>
      <div style={{ display: "flex", gap: 2 }}>
        {["Sparkles", "Search", "HelpCircle", "Settings"].map((n, i) => (
          <button key={i} style={{ padding: 6, background: "none", border: "none", cursor: "pointer", borderRadius: 6 }}>
            <Icon name={n} size={18} color={fg} />
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Icon, StatusBadge, Sparkline, LeftNav, TopNav });
})();
