// Consolidated 8-destination hubs — group existing pages under in-page sub-tabs.
// Reuses the real, working page components (now coral) so all data/actions keep
// functioning while the IA becomes the clean redesign. (page-hubs.jsx)

function CCHub({ storeKey, tabs }) {
  const visible = tabs.filter((t) => t.show !== false);
  const [tab, setTab] = React.useState(() => {
    try { const s = localStorage.getItem("clearcast-hub-" + storeKey); if (s && visible.some((t) => t.id === s)) return s; } catch (e) {}
    return visible[0]?.id;
  });
  const active = visible.find((t) => t.id === tab) || visible[0];
  const Comp = (active && window[active.comp]) || (() => <div className="page"><div className="card" style={{ padding: 28 }}>This section isn’t available.</div></div>);
  const go = (id) => { setTab(id); try { localStorage.setItem("clearcast-hub-" + storeKey, id); } catch (e) {} };
  return (
    <React.Fragment>
      <div className="hub-subnav">
        {visible.map((t) => (
          <button key={t.id} className={`hub-tab ${active && active.id === t.id ? "active" : ""}`} onClick={() => go(t.id)}>
            {t.icon && Icon[t.icon] ? React.createElement(Icon[t.icon], { className: "ico", width: 15, height: 15 }) : null}
            {t.label}
          </button>
        ))}
      </div>
      <Comp key={active && active.id} />
    </React.Fragment>
  );
}

function PlanHub() {
  return <CCHub storeKey="plan" tabs={[
    { id: "calendar", label: "Calendar", icon: "Calendar", comp: "CalendarPage" },
    { id: "published", label: "Published", icon: "Globe", comp: "PublishedPage" },
    { id: "bulk", label: "Bulk Upload", icon: "Upload", comp: "BulkUploadPage" },
    { id: "content", label: "Recycle & RSS", icon: "Refresh", comp: "ContentPage" },
    { id: "experiments", label: "A/B Tests", icon: "TrendUp", comp: "ExperimentsPage" },
  ]} />;
}

function EngageHub() {
  return <CCHub storeKey="engage" tabs={[
    { id: "inbox", label: "Inbox", icon: "Inbox", comp: "InboxPage" },
    { id: "contacts", label: "People", icon: "Users", comp: "ContactsPage" },
    { id: "reviews", label: "Reviews", icon: "Star", comp: "ReviewsPage" },
    { id: "listening", label: "Listening", icon: "Search", comp: "ListeningPage" },
    { id: "advocacy", label: "Advocacy & UGC", icon: "Heart", comp: "AdvocacyPage" },
  ]} />;
}

function AnalyzeHub() {
  return <CCHub storeKey="analyze" tabs={[
    { id: "analytics", label: "Analytics", icon: "Bar", comp: "AnalyticsPage" },
    { id: "benchmarking", label: "Benchmarks", icon: "Grid", comp: "BenchmarkingPage" },
    { id: "reports", label: "Reports", icon: "File", comp: "ReportsPage" },
  ]} />;
}

function GrowHub() {
  return <CCHub storeKey="grow" tabs={[
    { id: "ads", label: "Ads", icon: "TrendUp", comp: "AdsPage" },
    { id: "linkbio", label: "Link in Bio", icon: "Hash", comp: "LinkInBioPage" },
    { id: "links", label: "Short Links", icon: "Link", comp: "LinksPage" },
  ]} />;
}

function SettingsHub() {
  const hub = window.useClearCast();
  const isAdmin = !!(hub.data && hub.data.isAdmin);
  return <CCHub storeKey="settings" tabs={[
    { id: "general", label: "General", icon: "Settings", comp: "SettingsPage" },
    { id: "businesses", label: "Businesses", icon: "Grid", comp: "BusinessesPage" },
    { id: "team", label: "Team", icon: "Users", comp: "TeamPage" },
    { id: "integrations", label: "Integrations", icon: "Plug", comp: "IntegrationsPage" },
    { id: "billing", label: "Billing", icon: "Tag", comp: "BillingPage" },
    { id: "developer", label: "Developer / API", icon: "Lock", comp: "DeveloperPage" },
    { id: "agency", label: "Agency", icon: "Bookmark", comp: "AgencyPage" },
    { id: "admin", label: "Admin", icon: "Lock", comp: "AdminPage", show: isAdmin },
  ]} />;
}

// ---- Home dashboard -------------------------------------------------------
function HomeHub() {
  const hub = window.useClearCast();
  const data = hub.data || {};
  const posts = data.posts || [];
  const inbox = data.inbox || [];
  const businessName = (data.workspaces || []).find((w) => w.id === data.activeWorkspaceId)?.name || data.workspace?.name || "your workspace";
  const firstName = (data.workspace?.user?.name || data.authUser?.name || data.authUser?.email || "there").split(/[ @]/)[0];
  const scheduled = posts.filter((p) => p.status === "scheduled").length;
  const approvals = posts.filter((p) => ["needs_approval", "changes_requested"].includes(p.status)).length;
  const published = posts.filter((p) => p.status === "published").length;
  const openInbox = inbox.filter((m) => !m.archived && m.status !== "done").length;
  const todayKey = (() => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; })();
  const queue = posts.filter((p) => ["scheduled", "needs_approval", "changes_requested"].includes(p.status))
    .sort((a, b) => `${a.date} ${a.time}`.localeCompare(`${b.date} ${b.time}`)).slice(0, 6);

  const KPI = ({ label, value, sub, tone, to }) => (
    <button className="card hub-kpi" onClick={() => to && hub.setPage(to)} style={{ textAlign: "left", cursor: to ? "pointer" : "default" }}>
      <div className="muted" style={{ fontSize: 12 }}>{label}</div>
      <div style={{ fontSize: 28, fontWeight: 720, marginTop: 4, color: tone || "var(--text)" }}>{value}</div>
      <div className="faint" style={{ fontSize: 12, marginTop: 2 }}>{sub}</div>
    </button>
  );

  return (
    <div className="hub page-fade">
      <div className="hub-head">
        <div className="hub-head-l">
          <div className="hub-eyebrow"><Icon.Sparkles width="13" height="13" /> {businessName}</div>
          <h1>Welcome back, <em>{firstName}</em></h1>
          <div className="hub-sub">Here’s what needs you today — and the quickest way to keep things moving.</div>
        </div>
        <div className="hub-head-r">
          <button className="btn btn-primary" onClick={() => hub.setPage("create")}><Icon.Edit width="14" height="14" /> Create a post</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 18 }}>
        <KPI label="Scheduled" value={scheduled} sub="ready to go out" tone="var(--accent-2)" to="plan" />
        <KPI label="Awaiting approval" value={approvals} sub={approvals ? "needs review" : "all clear"} tone={approvals ? "var(--warn)" : "var(--text)"} to="approvals" />
        <KPI label="Open conversations" value={openInbox} sub="in your inbox" to="engage" />
        <KPI label="Published" value={published} sub="all time" to="plan" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.6fr) minmax(0,1fr)", gap: 16 }}>
        <div className="card">
          <div className="card-h"><h3>Up next</h3><a className="sub" style={{ color: "var(--accent-2)", cursor: "pointer" }} onClick={() => hub.setPage("plan")}>Open calendar</a></div>
          {queue.length === 0 ? (
            <div className="empty-note" style={{ margin: "12px 0" }}>Nothing queued yet — <a style={{ color: "var(--accent-2)", cursor: "pointer" }} onClick={() => hub.setPage("create")}>create your first post</a>.</div>
          ) : queue.map((p) => (
            <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--border)" }}>
              <div style={{ minWidth: 92 }}><span className="faint" style={{ fontSize: 12 }}>{p.date === todayKey ? "Today" : p.date} · {p.time}</span></div>
              <div style={{ display: "flex", gap: 4 }}>{(p.platforms || []).slice(0, 3).map((pf) => <PlatformIcon key={pf} id={pf} size={18} />)}</div>
              <div style={{ flex: 1, minWidth: 0, fontSize: 13, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.caption}</div>
              <span className={`pill ${p.status === "scheduled" ? "green" : "warn"}`} style={{ fontSize: 11 }}>{p.status === "scheduled" ? "Scheduled" : "Approval"}</span>
            </div>
          ))}
        </div>
        <div className="card">
          <div className="card-h"><h3>Quick actions</h3></div>
          <div style={{ display: "grid", gap: 8 }}>
            <button className="btn" style={{ justifyContent: "flex-start" }} onClick={() => hub.setPage("create")}><Icon.Edit width="15" height="15" /> Create a post</button>
            <button className="btn" style={{ justifyContent: "flex-start" }} onClick={() => hub.setPage("plan")}><Icon.Calendar width="15" height="15" /> Plan the calendar</button>
            <button className="btn" style={{ justifyContent: "flex-start" }} onClick={() => hub.setPage("approvals")}><Icon.Check width="15" height="15" /> Review approvals {approvals ? `(${approvals})` : ""}</button>
            <button className="btn" style={{ justifyContent: "flex-start" }} onClick={() => hub.setPage("engage")}><Icon.Inbox width="15" height="15" /> Reply in the inbox {openInbox ? `(${openInbox})` : ""}</button>
            <button className="btn" style={{ justifyContent: "flex-start" }} onClick={() => hub.setPage("analyze")}><Icon.Bar width="15" height="15" /> See analytics</button>
            <button className="btn" style={{ justifyContent: "flex-start" }} onClick={() => hub.setPage("settings")}><Icon.Plug width="15" height="15" /> Connect channels</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.PlanHub = PlanHub;
window.EngageHub = EngageHub;
window.AnalyzeHub = AnalyzeHub;
window.GrowHub = GrowHub;
window.SettingsHub = SettingsHub;
window.HomeHub = HomeHub;
