// Manage Businesses — rename, recolor, set timezone, switch, delete, and add
// the businesses (workspaces) in this account.

const BIZ_TIMEZONES = [
  "America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles",
  "America/Phoenix", "UTC", "Europe/London", "Europe/Paris", "Australia/Sydney"
];

function bizInitials(name) {
  return (name || "CC").split(/\s+/).map((w) => w[0]).filter(Boolean).join("").slice(0, 2).toUpperCase();
}

function BusinessRow({ workspace, isOnly, onSwitch, onSave, onDelete }) {
  const [name, setName] = React.useState(workspace.name || "");
  const [timezone, setTimezone] = React.useState(workspace.timezone || "America/New_York");
  const [color, setColor] = React.useState(workspace.brandColor || "#14b88a");
  const [busy, setBusy] = React.useState("");
  const dirty = name.trim() !== (workspace.name || "") || timezone !== (workspace.timezone || "America/New_York") || color !== (workspace.brandColor || "#14b88a");

  const save = async () => {
    if (!name.trim() || busy) return;
    setBusy("save");
    try { await onSave(workspace.id, { name: name.trim(), timezone, brandColor: color }); }
    finally { setBusy(""); }
  };
  const remove = async () => {
    if (isOnly) return;
    if (!window.confirm(`Delete "${workspace.name}"? This permanently removes its posts, media, inbox, and settings.`)) return;
    setBusy("delete");
    try { await onDelete(workspace.id); }
    finally { setBusy(""); }
  };

  return (
    <div className={`biz-row ${workspace.active ? "active" : ""}`}>
      <div className="biz-avatar" style={{ background: color }}>{bizInitials(name)}</div>
      <div className="biz-fields">
        <div className="biz-fields-top">
          <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Business name" style={{ fontWeight: 600 }} />
          <select className="input" value={timezone} onChange={(e) => setTimezone(e.target.value)}>
            {BIZ_TIMEZONES.map((tz) => <option key={tz} value={tz}>{tz}</option>)}
          </select>
          <label className="biz-color" title="Brand color">
            <input type="color" value={color} onChange={(e) => setColor(e.target.value)} />
          </label>
        </div>
        <div className="biz-meta muted">
          {workspace.active && <span className="pill" style={{ padding: "1px 7px", fontSize: 10, color: "var(--accent-2)", borderColor: "rgba(20,184,138,0.3)" }}>Active</span>}
          <span>{workspace.connectedChannels || 0} channels</span>
          <span>·</span>
          <span>{workspace.postCount || 0} posts</span>
          <span>·</span>
          <span style={{ textTransform: "capitalize" }}>{workspace.plan || "free"} plan</span>
        </div>
      </div>
      <div className="biz-actions">
        {!workspace.active && <button className="btn btn-sm" disabled={!!busy} onClick={() => onSwitch(workspace.id)}>Open</button>}
        <button className="btn btn-sm btn-primary" disabled={!dirty || !!busy} onClick={save}>{busy === "save" ? "Saving…" : "Save"}</button>
        <button className="btn btn-sm" disabled={isOnly || !!busy} title={isOnly ? "You must keep at least one business" : "Delete business"} onClick={remove} style={{ color: isOnly ? "var(--text-3)" : "var(--danger)" }}>{busy === "delete" ? "…" : "Delete"}</button>
      </div>
    </div>
  );
}

function BusinessesPage() {
  const hub = window.useClearCast();
  const data = hub.data || {};
  const workspaces = data.workspaces || [];
  const [newName, setNewName] = React.useState("");
  const [adding, setAdding] = React.useState(false);

  const addBusiness = async () => {
    if (!newName.trim() || adding) return;
    setAdding(true);
    try { await hub.actions.createWorkspace({ name: newName.trim() }); setNewName(""); }
    finally { setAdding(false); }
  };

  return (
    <div className="page businesses-page">
      <div className="card" style={{ padding: 20, marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 15 }}>Your businesses</h3>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>Each business has its own channels, posts, inbox, analytics, and billing. Collaborator seats are free across all of them.</div>
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <input className="input" value={newName} onChange={(e) => setNewName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") addBusiness(); }} placeholder="New business name" style={{ width: 200 }} />
            <button className="btn btn-primary" disabled={!newName.trim() || adding} onClick={addBusiness}><Icon.Plus width="14" height="14" /> {adding ? "Adding…" : "Add business"}</button>
          </div>
        </div>
      </div>

      <div className="biz-list">
        {workspaces.map((workspace) => (
          <BusinessRow
            key={workspace.id}
            workspace={workspace}
            isOnly={workspaces.length <= 1}
            onSwitch={(id) => hub.actions.switchWorkspace(id)}
            onSave={(id, payload) => hub.actions.renameWorkspace(id, payload)}
            onDelete={(id) => hub.actions.deleteWorkspace(id)}
          />
        ))}
      </div>
    </div>
  );
}

window.BusinessesPage = BusinessesPage;
