// Recursive MLS — shared chrome (icons, header, sidebar) + small atoms.
const { useState, useEffect, useRef } = React;

// ---- Lucide icon as pure React SVG (no DOM mutation — safe under React) ----
const _pascal = (n) => n.split("-").map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
const _camel = (k) => k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
function Icon({ name, size = 18, color, stroke = 2, style }) {
  const node = (window.lucide && window.lucide.icons && window.lucide.icons[_pascal(name)]) || [];
  const kids = node.map((child, i) => {
    const [tag, attrs] = child;
    const props = { key: i };
    for (const k in attrs) props[_camel(k)] = attrs[k];
    return React.createElement(tag, props);
  });
  return React.createElement("svg", {
    width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: color || "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round",
    style: { display: "inline-block", flex: "none", verticalAlign: "middle", ...style },
  }, kids);
}
function refreshIcons() { /* no-op: icons render via React now */ }

// ---- Status pill ----
function Pill({ children, tone = "active", style }) {
  const tones = {
    active:   { bg: "#e8f4ee", fg: "#1f8a5b" },
    pending:  { bg: "#fbf2dc", fg: "#9a6a12" },
    drop:     { bg: "#faece3", fg: "#c0612f" },
    new:      { bg: "#006747", fg: "#fff" },
    neutral:  { bg: "#f0efe9", fg: "#6b706a" },
  };
  const t = tones[tone] || tones.neutral;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, fontWeight: 600,
      letterSpacing: ".3px", padding: "4px 9px", borderRadius: 999, background: t.bg, color: t.fg,
      whiteSpace: "nowrap", lineHeight: 1, ...style }}>
      {children}
    </span>
  );
}

// ---- Header ----
function Header({ light, query, setQuery }) {
  const bg = light ? "#ffffff" : "#006747";
  const fg = light ? "#1d241f" : "#ffffff";
  const sub = light ? "#8a8e88" : "rgba(255,255,255,.6)";
  const fieldBg = light ? "#f4f3ef" : "rgba(255,255,255,.12)";
  const fieldBd = light ? "#e7e5df" : "rgba(255,255,255,.16)";
  const fieldFg = light ? "#1d241f" : "#fff";
  const iconC = light ? "#8a8e88" : "rgba(255,255,255,.8)";
  const markStroke = light ? "#006747" : "#fff";
  return (
    <header style={{ gridColumn: "1 / 3", background: bg, display: "flex", alignItems: "center",
      padding: "0 22px", gap: 16, borderBottom: light ? "1px solid #e7e5df" : "none",
      boxShadow: light ? "0 1px 2px rgba(0,0,0,.04)" : "0 1px 0 rgba(0,0,0,.12)", zIndex: 6 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 11, width: 218, flex: "none" }}>
        <svg width="32" height="32" viewBox="0 0 100 100" style={{ flex: "none" }}>
          <rect x="13" y="13" width="74" height="74" rx="2" fill="none" stroke={markStroke} strokeWidth="6" />
          <g transform="translate(50,50) scale(0.78) translate(-50,-52)">
            <path d="M18 80 A8 8 0 0 1 34 80 A8 8 0 0 1 50 80 A8 8 0 0 1 66 80 A8 8 0 0 1 82 80 M26 64 A8 8 0 0 1 42 64 A8 8 0 0 1 58 64 A8 8 0 0 1 74 64 M34 48 A8 8 0 0 1 50 48 A8 8 0 0 1 66 48 M42 32 A8 8 0 0 1 58 32"
              fill="none" stroke={markStroke} strokeWidth="7" strokeLinecap="round" />
          </g>
        </svg>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
          <span style={{ fontWeight: 600, fontSize: 19, letterSpacing: "-0.6px", color: fg }}>Recursive</span>
          <span style={{ fontWeight: 500, fontSize: 10, letterSpacing: "2px", textTransform: "uppercase", color: sub }}>MLS</span>
        </div>
      </div>

      <div style={{ flex: 1, maxWidth: 440, display: "flex", alignItems: "center", gap: 9,
        background: fieldBg, border: `1px solid ${fieldBd}`, borderRadius: 7, padding: "9px 12px" }}>
        <Icon name="search" size={16} color={iconC} />
        <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search the MLS — address, MLS #, area…"
          style={{ flex: 1, border: 0, background: "transparent", outline: 0, fontFamily: "inherit", fontSize: 13, color: fieldFg }} />
        <span style={{ fontSize: 11, color: light ? "#b0b4ad" : "rgba(255,255,255,.45)",
          border: `1px solid ${light ? "#e0ded6" : "rgba(255,255,255,.2)"}`, borderRadius: 4, padding: "1px 6px" }}>⌘K</span>
      </div>

      <div style={{ flex: 1 }} />

      <div style={{ display: "flex", alignItems: "center", gap: 8, background: fieldBg,
        border: `1px solid ${fieldBd}`, borderRadius: 7, padding: "7px 11px", cursor: "pointer" }}>
        <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#1f8a5b" }} />
        <span style={{ fontSize: 12, fontWeight: 500, color: fg }}>Miami · MLS</span>
        <Icon name="chevron-down" size={15} color={iconC} />
      </div>

      <button style={{ position: "relative", border: 0, background: "transparent", cursor: "pointer", display: "flex", padding: 6 }}>
        <Icon name="bell" size={20} color={light ? "#4a504a" : "rgba(255,255,255,.9)"} />
        <span style={{ position: "absolute", top: 3, right: 3, width: 7, height: 7, borderRadius: "50%",
          background: "#e0a020", border: `1.5px solid ${bg}` }} />
      </button>
      <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#e7e1d4", color: "#006747",
        display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 13, cursor: "pointer" }}>AM</div>
    </header>
  );
}

// ---- Sidebar ----
const NAV = [
  { group: null, items: [{ icon: "layout-dashboard", label: "Dashboard", screen: "dashboard" }] },
  { group: "Listings", items: [
    { icon: "list-plus", label: "Add listing", screen: "listing" },
    { icon: "home", label: "My listings", screen: "mylistings", badge: "4" },
    { icon: "calendar-clock", label: "Showings", screen: "showings", badge: "2" },
  ] },
  { group: "Clients", items: [
    { icon: "search", label: "Find homes", screen: "search" },
    { icon: "users", label: "Clients", screen: "clients" },
    { icon: "heart", label: "Saved & alerts" },
  ] },
  { group: "Business", items: [
    { icon: "briefcase", label: "Pipeline" },
    { icon: "file-signature", label: "Offers", screen: "offers", badge: "3" },
    { icon: "bar-chart-3", label: "Market Insights", screen: "market" },
    { icon: "inbox", label: "Inbox", screen: "inbox", badge: (function () { try { const I = window.RC_INBOX; return String(I.activity.filter((a) => a.unread && a.kind !== "message").length + Object.values(I.unread).reduce((s, n) => s + n, 0)); } catch (e) { return "3"; } })() },
  ] },
  { group: "Tools", items: [
    { icon: "calculator", label: "CMA", href: "../../Recursive%20MLS%20-%20CMA.dc.html", external: true },
    { icon: "megaphone", label: "Marketing Kit", href: "../../Recursive%20MLS%20-%20Marketing%20Kit.dc.html", external: true },
  ] },
  { group: "Administrator", items: [
    { icon: "layout-dashboard", label: "Admin dashboard", screen: "admin" },
    { icon: "users-round", label: "Agents & users", screen: "admin_users" },
    { icon: "shield-check", label: "Compliance", screen: "admin_compliance", badge: "12" },
    { icon: "lock", label: "Roles & permissions", screen: "admin_roles" },
    { icon: "message-square-warning", label: "Moderation", screen: "admin_moderation", badge: "5" },
  ] },
];

function Sidebar({ light, screen, go }) {
  return (
    <nav style={{ background: light ? "#faf9f5" : "#fff", borderRight: "1px solid #ececec",
      padding: "14px 12px", display: "flex", flexDirection: "column", overflowY: "auto", gap: 2 }}>
      {NAV.map((sec, si) => (
        <div key={si} style={{ marginTop: sec.group ? 16 : 0 }}>
          {sec.group && (
            <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "1.5px", textTransform: "uppercase",
              color: "#a8aca6", padding: "0 10px 7px" }}>{sec.group}</div>
          )}
          {sec.items.map((it, ii) => {
            const active = it.screen && it.screen === screen;
            return (
              <div key={ii} className="rc-nav-item" onClick={() => { if (it.screen) go(it.screen); else if (it.href) window.open(it.href, "_blank", "noopener,noreferrer"); }}
                style={{ position: "relative", display: "flex", alignItems: "center", gap: 11,
                  padding: "9px 12px", borderRadius: 7, cursor: (it.screen || it.href) ? "pointer" : "default",
                  background: active ? "#eef4f1" : "transparent",
                  color: active ? "#006747" : "#4a504a", fontWeight: active ? 600 : 400, fontSize: 14 }}>
                {active && <span style={{ position: "absolute", left: -12, top: 8, bottom: 8, width: 3, borderRadius: 3, background: "#006747" }} />}
                <Icon name={it.icon} size={18} color={active ? "#006747" : "#8a8e88"} stroke={active ? 2.2 : 2} />
                <span style={{ flex: 1 }}>{it.label}</span>
                {it.badge && (
                  <span style={{ fontSize: 11, fontWeight: 600, color: "#006747", background: "#e8f1ec",
                    borderRadius: 999, padding: "1px 7px" }}>{it.badge}</span>
                )}
                {it.external && <Icon name="arrow-up-right" size={14} color="#a8aca6" />}
              </div>
            );
          })}
        </div>
      ))}
      <div style={{ flex: 1 }} />
      <div style={{ borderTop: "1px solid #ececec", margin: "8px 4px", paddingTop: 10 }}>
        <div className="rc-nav-item" style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 12px", borderRadius: 7, color: "#4a504a", fontSize: 14, cursor: "pointer" }}>
          <Icon name="settings" size={18} color="#8a8e88" /><span>Settings</span>
        </div>
      </div>
    </nav>
  );
}

Object.assign(window, { Icon, refreshIcons, Pill, Header, Sidebar });
