// Recursive MLS — Admin screen: Feature flags.
// MLS admins enable/disable platform modules per their MLS. CMA & Pricing is a flag here.
// In production each flag is read by BOTH controllers (Lattice + Displet) at request time.
function AdminFeatures() {
  const initial = [
    { id: "cma", label: "CMA & Pricing", icon: "calculator", group: "Agent tools",
      desc: "Comparative market analysis — MLS + AI comps, AI pricing, branded report, tracked share link & PDF.",
      on: true, rollout: "All agents", stage: "GA", controllers: ["Lattice", "Displet"] },
    { id: "marketing", label: "Listing marketing kit", icon: "megaphone", group: "Agent tools",
      desc: "Auto-generated branded assets, single-property site, and one-click social scheduling on publish.",
      on: true, rollout: "All agents", stage: "GA", controllers: ["Lattice", "Displet"] },
    { id: "showings", label: "Showings", icon: "calendar-clock", group: "Agent tools",
      desc: "Scheduling, calendar sync, route planning, and post-tour feedback.",
      on: true, rollout: "All agents", stage: "GA", controllers: ["Lattice", "Displet"] },
    { id: "listing_detail", label: "Listing detail + neighborhood", icon: "map-pinned", group: "Agent tools",
      desc: "Agent-facing detail page with Local Logic map and Census demographics.",
      on: true, rollout: "All agents", stage: "GA", controllers: ["Lattice"] },
    { id: "inbox", label: "Messaging / Inbox", icon: "message-circle", group: "Communication",
      desc: "Agent-to-agent and agent-to-client messaging with policy moderation.",
      on: true, rollout: "All agents", stage: "GA", controllers: ["Lattice"] },
    { id: "kb", label: "Knowledgebase & LMS", icon: "graduation-cap", group: "Learn & support",
      desc: "Training content, learning paths, quizzes, SCORM import/export.",
      on: true, rollout: "All agents", stage: "Beta", controllers: ["Lattice"] },
    { id: "support", label: "Support ticketing", icon: "life-buoy", group: "Learn & support",
      desc: "Multi-channel tickets (form / email / phone / SMS) with KB deflection.",
      on: true, rollout: "All agents", stage: "Beta", controllers: ["Lattice", "Displet"] },
    { id: "deeplinks", label: "Partner deep-links", icon: "external-link", group: "Integrations",
      desc: "RPR, Cloud CMA, Realist and other partner links on the listing detail page.",
      on: true, rollout: "All agents", stage: "GA", controllers: ["Lattice"] },
    { id: "ai_chat", label: "Ask Recursive AI", icon: "sparkles", group: "Communication",
      desc: "In-app AI assistant answering from the published knowledgebase.",
      on: false, rollout: "Staff only", stage: "Pilot", controllers: ["Displet"] },
    { id: "transactions", label: "Transaction deal room", icon: "file-signature", group: "Agent tools",
      desc: "Contract-to-close workspace: deadlines, documents, and e-sign.",
      on: false, rollout: "Off", stage: "Coming soon", controllers: ["Lattice", "Displet"] },
  ];
  const [flags, setFlags] = useState(initial);
  const [picker, setPicker] = useState(null); // flag id whose rollout dropdown is open
  const toggle = (id) => setFlags(flags.map((f) => f.id === id ? { ...f, on: !f.on, rollout: !f.on ? "All agents" : "Off" } : f));
  const setRollout = (id, r) => setFlags(flags.map((f) => f.id === id ? { ...f, rollout: r, on: r !== "Off" } : f));

  const stageTone = (s) => ({ GA: ["#eef4f1", "#006747"], Beta: ["#eef1f6", "#16243A"], Pilot: ["#faece3", "#c0612f"], "Coming soon": ["#f0efe9", "#8a8e88"] }[s] || ["#f0efe9", "#6b706a"]);
  const groups = ["Agent tools", "Communication", "Learn & support", "Integrations"];
  const onCount = flags.filter((f) => f.on).length;

  return (
    <div style={{ height: "100%", overflowY: "auto", background: "#f4f3ef" }}>
      <div style={{ maxWidth: 1080, margin: "0 auto", padding: "26px 28px 64px" }}>

        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 18, flexWrap: "wrap", marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1.5px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 6 }}>Administrator · Feature flags</div>
            <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px" }}>Modules &amp; rollout</h1>
            <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>Turn platform features on or off for your MLS and control who sees them. {onCount} of {flags.length} enabled.</p>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 9, background: "#eef4f1", border: "1px solid #d6e7de", borderRadius: 8, padding: "9px 13px" }}>
            <Icon name="info" size={15} color="#006747" />
            <span style={{ fontSize: 12, color: "#3a463f", maxWidth: 320, lineHeight: 1.45 }}>Flags are enforced by both the Lattice and Displet controllers at request time.</span>
          </div>
        </div>

        {groups.map((g) => (
          <div key={g} style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#a8aca6", marginBottom: 10 }}>{g}</div>
            <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", overflow: "hidden" }}>
              {flags.filter((f) => f.group === g).map((f, i, arr) => {
                const [bg, fg] = stageTone(f.stage);
                return (
                  <div key={f.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 18px", borderBottom: i < arr.length - 1 ? "1px solid #f4f3ee" : "none", background: f.on ? "#fff" : "#fbfaf7" }}>
                    <span style={{ width: 40, height: 40, borderRadius: 9, background: f.on ? "#eef4f1" : "#f0efe9", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
                      <Icon name={f.icon} size={19} color={f.on ? "#006747" : "#a8aca6"} />
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                        <span style={{ fontSize: 14.5, fontWeight: 600, color: f.on ? "#1d241f" : "#6b706a" }}>{f.label}</span>
                        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", color: fg, background: bg, borderRadius: 4, padding: "2px 7px" }}>{f.stage}</span>
                        {f.id === "cma" && <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", color: "#c0612f", background: "#faece3", borderRadius: 4, padding: "2px 7px" }}>New</span>}
                      </div>
                      <div style={{ fontSize: 12.5, color: "#8a8e88", marginTop: 3, lineHeight: 1.45 }}>{f.desc}</div>
                      <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 7 }}>
                        <span style={{ fontSize: 10.5, color: "#a8aca6", textTransform: "uppercase", letterSpacing: ".4px" }}>Controllers</span>
                        {f.controllers.map((c) => (
                          <span key={c} style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10.5, fontWeight: 600, color: c === "Lattice" ? "#006747" : "#16243A", background: c === "Lattice" ? "#eef4f1" : "#eef1f6", borderRadius: 4, padding: "2px 7px" }}>
                            <Icon name={c === "Lattice" ? "database" : "server" } size={11} color={c === "Lattice" ? "#006747" : "#16243A"} /> {c}
                          </span>
                        ))}
                      </div>
                    </div>

                    {/* rollout selector */}
                    <div style={{ position: "relative", flex: "none" }}>
                      <button onClick={() => setPicker(picker === f.id ? null : f.id)} disabled={!f.on}
                        style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: f.on ? "#4a504a" : "#bcbfba", background: "#fff", border: "1px solid #e2e0d8", borderRadius: 7, padding: "7px 11px", cursor: f.on ? "pointer" : "not-allowed" }}>
                        <Icon name="users" size={13} color={f.on ? "#8a8e88" : "#cdcdc4"} /> {f.rollout} <Icon name="chevron-down" size={13} color="#a8aca6" />
                      </button>
                      {picker === f.id && f.on && (
                        <div style={{ position: "absolute", right: 0, top: "calc(100% + 4px)", width: 180, background: "#fff", borderRadius: 8, boxShadow: "0 8px 28px rgba(0,0,0,.18)", border: "1px solid #ececec", zIndex: 10, overflow: "hidden" }}>
                          {["All agents", "By office", "Beta group", "Staff only"].map((r) => (
                            <div key={r} onClick={() => { setRollout(f.id, r); setPicker(null); }} className="rc-nav-item" style={{ padding: "9px 12px", fontSize: 12.5, color: f.rollout === r ? "#006747" : "#4a504a", fontWeight: f.rollout === r ? 600 : 400, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                              {r}{f.rollout === r && <Icon name="check" size={14} color="#006747" />}
                            </div>
                          ))}
                        </div>
                      )}
                    </div>

                    {/* on/off toggle */}
                    <button onClick={() => toggle(f.id)} title={f.on ? "Disable" : "Enable"} style={{ position: "relative", width: 44, height: 24, borderRadius: 999, border: 0, cursor: "pointer", background: f.on ? "#006747" : "#d2d0c7", flex: "none", transition: "background .15s" }}>
                      <span style={{ position: "absolute", top: 2, left: f.on ? 22 : 2, width: 20, height: 20, borderRadius: "50%", background: "#fff", boxShadow: "0 1px 3px rgba(0,0,0,.3)", transition: "left .15s" }} />
                    </button>
                  </div>
                );
              })}
            </div>
          </div>
        ))}

        <div style={{ display: "flex", alignItems: "flex-start", gap: 9, background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "14px 16px", fontSize: 12, color: "#6b706a", lineHeight: 1.55 }}>
          <Icon name="git-branch" size={15} color="#8a8e88" style={{ marginTop: 1, flex: "none" }} />
          <span>Each flag's state is published to both controllers. The <strong style={{ color: "#006747", fontWeight: 600 }}>Lattice</strong> controller gates MLS-data endpoints (records, governance); the <strong style={{ color: "#16243A", fontWeight: 600 }}>Displet</strong> controller gates app endpoints (agent artifacts, scheduling). A feature only appears for an agent when enabled and in scope on both.</span>
        </div>
      </div>
    </div>
  );
}
window.AdminFeatures = AdminFeatures;
