/* NutriDMS enterprise workspace control center. Server data is authoritative. */
(function () {
  const { useEffect, useMemo, useState } = React;
  const emptyDraft = {
    name: "", location_code: "", region: "us-east", address_line: "", city: "",
    country: "", company_type: "", database_mode: "dedicated", shared_features: [],
    sync_enabled: false, sync_frequency: "manual",
  };
  const featureNames = {
    recipes: "Recipes", ingredients: "Ingredients", products: "Products",
    labels: "Labels", compliance: "Compliance", costing: "Costing",
    gs1: "GS1", customer_experiences: "Customer experience",
    digital_signage: "Digital signage",
  };
  const money = (value) => new Intl.NumberFormat(undefined, {
    style: "currency", currency: "USD", maximumFractionDigits: 0,
  }).format(Number(value || 0));
  const dateTime = (value) => value ? new Date(value).toLocaleString() : "Never";
  const initials = (name) => String(name || "?").trim().split(/\s+/).slice(0, 2)
    .map((part) => part.charAt(0)).join("").toUpperCase();

  function WorkspaceDrawer() {
    const I = window.Icon || (() => null);
    const [open, setOpen] = useState(false);
    const [hub, setHub] = useState(null);
    const [selectedId, setSelectedId] = useState("");
    const [details, setDetails] = useState(null);
    const [tab, setTab] = useState("overview");
    const [creating, setCreating] = useState(false);
    const [draft, setDraft] = useState(emptyDraft);
    const [busy, setBusy] = useState("");
    const [error, setError] = useState("");
    const [notice, setNotice] = useState("");

    const selected = useMemo(() => {
      const list = hub && hub.workspaces || [];
      return list.find((item) => String(item.id) === String(selectedId)) || list[0] || null;
    }, [hub, selectedId]);

    async function loadHub(preferred) {
      setBusy("load"); setError("");
      try {
        if (!window.NutriWorkspaces) throw new Error("Workspace service is unavailable.");
        const data = await window.NutriWorkspaces.hub();
        setHub(data);
        setSelectedId(String(preferred || data.active_workspace_id || (data.workspaces[0] || {}).id || ""));
      } catch (err) {
        setError(err.message || "Could not load workspaces.");
      } finally { setBusy(""); }
    }

    async function loadDetails(id) {
      if (!id || !window.NutriWorkspaces) return;
      try { setDetails((await window.NutriWorkspaces.get(id))); }
      catch (err) { setError(err.message || "Could not load workspace details."); }
    }

    useEffect(() => {
      const show = () => { setOpen(true); setCreating(false); setTab("overview"); loadHub(); };
      const close = (event) => { if (event.key === "Escape") setOpen(false); };
      window.addEventListener("nutridms-open-workspace", show);
      window.addEventListener("keydown", close);
      return () => {
        window.removeEventListener("nutridms-open-workspace", show);
        window.removeEventListener("keydown", close);
      };
    }, []);

    useEffect(() => {
      if (open && selectedId && !creating) loadDetails(selectedId);
    }, [open, selectedId, creating]);

    async function switchWorkspace(id) {
      if (!hub || !hub.can_switch || String(id) === String(hub.active_workspace_id)) {
        setSelectedId(String(id)); return;
      }
      setBusy("switch"); setError("");
      try {
        await window.NutriWorkspaces.switchTo(id);
        setNotice("Workspace switched. Loading live location data…");
        window.setTimeout(() => window.top.location.reload(), 250);
      } catch (err) { setError(err.message || "Could not switch workspace."); }
      finally { setBusy(""); }
    }

    async function createWorkspace() {
      setBusy("create"); setError(""); setNotice("");
      try {
        const address = {
          line1: draft.address_line, city: draft.city, country: draft.country,
          formatted: [draft.address_line, draft.city, draft.country].filter(Boolean).join(", "),
        };
        const payload = {
          name: draft.name, location_code: draft.location_code, region: draft.region,
          address, company_profile: { company_type: draft.company_type },
          database_mode: draft.database_mode, shared_features: draft.shared_features,
          sync_enabled: draft.sync_enabled, sync_frequency: draft.sync_frequency,
          branding: { use_hq_branding: true },
        };
        const data = await window.NutriWorkspaces.create(payload);
        setNotice(data.email_queued === false
          ? "Workspace created. The email notice is being retried."
          : "Workspace created and confirmation email queued.");
        setCreating(false); setDraft(emptyDraft);
        await loadHub(data.workspace.id);
      } catch (err) { setError(err.message || "Could not create workspace."); }
      finally { setBusy(""); }
    }

    async function updateWorkspace(patch, success) {
      if (!selected) return;
      setBusy("save"); setError(""); setNotice("");
      try {
        const data = await window.NutriWorkspaces.update(selected.id, patch);
        setDetails(data); setNotice(success || "Workspace settings saved.");
        await loadHub(selected.id);
      } catch (err) { setError(err.message || "Could not save workspace."); }
      finally { setBusy(""); }
    }

    async function runSync(restoreSince) {
      if (!selected) return;
      setBusy("sync"); setError(""); setNotice("");
      try {
        const payload = restoreSince ? { restore_since: new Date(restoreSince).toISOString() } : {};
        const data = await window.NutriWorkspaces.sync(selected.id, payload);
        setNotice(restoreSince
          ? (data.result.records_restored + " record(s) restored and synchronized.")
          : "Workspace data synchronized.");
        await loadHub(selected.id); await loadDetails(selected.id);
      } catch (err) { setError(err.message || "Synchronization failed."); }
      finally { setBusy(""); }
    }

    function toggleFeature(feature) {
      setDraft((current) => ({
        ...current,
        shared_features: current.shared_features.includes(feature)
          ? current.shared_features.filter((item) => item !== feature)
          : [...current.shared_features, feature],
      }));
    }

    if (!open) return null;
    const workspace = details && details.workspace || selected;
    const branding = workspace && workspace.branding || {};
    const billing = hub && hub.billing || {};
    const members = details && details.members || [];
    const activity = details && details.activity || [];

    return (
      <div className="wsd-scrim" onMouseDown={(event) => event.target === event.currentTarget && setOpen(false)}>
        <section className="wsd" role="dialog" aria-modal="true" aria-label="Workspace management">
          <header className="wsd-head">
            <div className="wsd-head-t"><span className="wsd-ic"><I name="boxes" size={18} /></span>
              <div><strong>Workspaces</strong><span>Enterprise locations, data and branding</span></div>
            </div>
            <button className="wsd-x" onClick={() => setOpen(false)} aria-label="Close"><I name="x" size={18} /></button>
          </header>

          <div className="wsd-body">
            <aside className="wsd-switch">
              <div className="wsd-lbl">Switch workspace</div>
              {busy === "load" && !hub && <div className="wsd-empty">Loading live workspaces…</div>}
              {(hub && hub.workspaces || []).map((item) => (
                <button key={item.id} className={"wsd-ws" + (String(item.id) === String(selectedId) ? " on" : "")}
                  disabled={busy === "switch"} onClick={() => { setCreating(false); switchWorkspace(item.id); }}>
                  <span className="wsd-av">{branding.logo_url && String(item.id) === String(selectedId)
                    ? <img src={branding.logo_url} alt="" /> : initials(item.name)}</span>
                  <span className="wsd-ws-tx"><strong>{item.name}</strong>
                    <small>{item.is_headquarters ? "Headquarters" : item.location_code || "Location"} · {item.members} members</small>
                  </span>
                  {String(item.id) === String(hub.active_workspace_id) ? <I name="check" size={16} /> : <I name="chevron-right" size={15} />}
                </button>
              ))}
              {hub && hub.can_create && <button className="wsd-add" onClick={() => { setCreating(true); setError(""); }}>
                <I name="plus" size={16} /> New workspace
              </button>}
              {hub && !hub.can_create && <p className="wsd-enterprise-note">Enterprise is required for additional locations.</p>}
            </aside>

            <main className="wsd-main">
              {(error || notice) && <div className={"wsd-alert " + (error ? "error" : "success")}>{error || notice}</div>}
              {creating ? (
                <div className="wsd-pane wsd-create">
                  <div className="wsd-title"><div><strong>Create workspace location</strong>
                    <span>Each location is a tenant with its own address, access boundary and sharing policy.</span></div>
                  </div>
                  <div className="wsd-grid">
                    <label className="wsd-field"><span>Location name</span><input autoFocus value={draft.name} onChange={(e) => setDraft({...draft, name:e.target.value})} /></label>
                    <label className="wsd-field"><span>Location code</span><input value={draft.location_code} onChange={(e) => setDraft({...draft, location_code:e.target.value})} placeholder="Auto-generated" /></label>
                    <label className="wsd-field full"><span>Street address</span><input value={draft.address_line} onChange={(e) => setDraft({...draft, address_line:e.target.value})} /></label>
                    <label className="wsd-field"><span>City</span><input value={draft.city} onChange={(e) => setDraft({...draft, city:e.target.value})} /></label>
                    <label className="wsd-field"><span>Country</span><input value={draft.country} onChange={(e) => setDraft({...draft, country:e.target.value})} /></label>
                    <label className="wsd-field"><span>Company profile</span><input value={draft.company_type} onChange={(e) => setDraft({...draft, company_type:e.target.value})} placeholder="Factory, restaurant, clinic…" /></label>
                    <label className="wsd-field"><span>Region</span><select value={draft.region} onChange={(e) => setDraft({...draft, region:e.target.value})}>
                      <option value="us-east">US East</option><option value="us-west">US West</option>
                      <option value="eu-west">EU West</option><option value="uk">United Kingdom</option>
                    </select></label>
                    <label className="wsd-field"><span>Database policy</span><select value={draft.database_mode} onChange={(e) => setDraft({...draft, database_mode:e.target.value})}>
                      <option value="dedicated">Dedicated — isolated</option><option value="shared">Shared — all selected data live</option>
                      <option value="hybrid">Hybrid — selected features</option>
                    </select></label>
                    <label className="wsd-field"><span>Sync schedule</span><select value={draft.sync_frequency} onChange={(e) => setDraft({...draft, sync_frequency:e.target.value, sync_enabled:e.target.value !== "manual"})}>
                      <option value="manual">Manual</option><option value="daily">Daily</option><option value="weekly">Weekly</option>
                    </select></label>
                  </div>
                  {draft.database_mode === "hybrid" && <div className="wsd-feature-box"><span>Shared software features</span>
                    <div className="wsd-check-grid">{(hub.shareable_features || []).map((feature) =>
                      <label key={feature}><input type="checkbox" checked={draft.shared_features.includes(feature)} onChange={() => toggleFeature(feature)} /> {featureNames[feature] || feature}</label>
                    )}</div>
                  </div>}
                  <div className="wsd-actions"><button className="wsd-ghost" onClick={() => setCreating(false)}>Cancel</button>
                    <button className="wsd-cta" disabled={!draft.name.trim() || busy === "create"} onClick={createWorkspace}>
                      <I name="check" size={15} /> {busy === "create" ? "Creating…" : "Create live workspace"}
                    </button></div>
                </div>
              ) : workspace ? (<>
                <nav className="wsd-tabs">
                  {[["overview","Overview"],["data","Data & Sync"],["branding","White-label"],["billing","Billing & Usage"],["people","Members & Logs"]].map(([id,label]) =>
                    <button key={id} className={tab === id ? "on" : ""} onClick={() => setTab(id)}>{label}</button>)}
                </nav>
                {tab === "overview" && <div className="wsd-pane">
                  <div className="wsd-title"><div><strong>{workspace.name}</strong><span>{workspace.address && workspace.address.formatted || workspace.region} · {workspace.is_headquarters ? "Headquarters" : workspace.location_code}</span></div>
                    <span className="wsd-live">Live</span></div>
                  <div className="wsd-kpis">
                    {[["Members",workspace.members,"users"],["Recipes",workspace.recipes,"utensils-crossed"],["Ingredients",workspace.ingredients,"wheat"],["AI tokens",workspace.ai_tokens_used,"sparkles"]].map(([label,value,icon]) =>
                      <div className="wsd-kpi" key={label}><I name={icon} size={16} /><b>{Number(value || 0).toLocaleString()}</b><span>{label}</span></div>)}
                  </div>
                  <div className="wsd-info-grid">
                    <div><span>Database</span><b>{workspace.database_mode}</b></div>
                    <div><span>Last sync</span><b>{dateTime(workspace.last_synced_at)}</b></div>
                    <div><span>Next sync</span><b>{dateTime(workspace.next_sync_at)}</b></div>
                    <div><span>Company profile</span><b>{workspace.company_profile && workspace.company_profile.company_type || "Not set"}</b></div>
                  </div>
                  {String(workspace.id) !== String(hub.active_workspace_id) && <button className="wsd-cta" onClick={() => switchWorkspace(workspace.id)}>Switch to this workspace</button>}
                </div>}
                {tab === "data" && <DataPane workspace={workspace} busy={busy} updateWorkspace={updateWorkspace} runSync={runSync} features={hub.shareable_features || []} />}
                {tab === "branding" && <BrandPane workspace={workspace} branding={branding} busy={busy} updateWorkspace={updateWorkspace} />}
                {tab === "billing" && <div className="wsd-pane">
                  <div className="wsd-note"><I name="credit-card" size={15} /> One Enterprise subscription is shared across locations. AI tokens remain location-specific.</div>
                  <div className="wsd-bill-grid">
                    <div><span>Enterprise base</span><b>{money(billing.base_monthly)}/mo</b></div>
                    <div><span>Locations</span><b>{billing.location_count} / {billing.included_locations} included</b></div>
                    <div><span>Additional locations</span><b>{billing.billable_locations} · {money(billing.location_overage_monthly)}/mo</b></div>
                    <div><span>Unique users</span><b>{billing.user_count} / {billing.included_users} included</b></div>
                    <div><span>Additional users</span><b>{billing.billable_users} · {money(billing.user_overage_monthly)}/mo</b></div>
                    <div><span>Paid add-ons</span><b>{money(billing.add_on_monthly)}/mo</b></div>
                  </div>
                  <div className="wsd-total"><span>Estimated subscription</span><b>{money(billing.estimated_monthly)}/month</b></div>
                  <p className="wsd-muted">Invoice and in-app notices are generated when a billable location, user, or add-on changes.</p>
                </div>}
                {tab === "people" && <div className="wsd-pane">
                  <div className="wsd-split">
                    <section><h3>Members at this location</h3>{members.length ? members.map((member) =>
                      <div className="wsd-member" key={member.id}><span className="wsd-userpic">{member.profile_picture_url ? <img src={member.profile_picture_url} alt="" /> : initials(member.user_name || member.user_email)}</span>
                        <div><b>{member.user_name || member.user_email}</b><small>{member.role_label} · {member.member_status}</small></div></div>
                    ) : <p className="wsd-muted">No active members in this location.</p>}</section>
                    <section><h3>Location audit log</h3>{activity.length ? activity.map((item) =>
                      <div className="wsd-log" key={item.id}><b>{item.action}</b><small>{dateTime(item.created_at)}</small></div>
                    ) : <p className="wsd-muted">No activity has been recorded yet.</p>}</section>
                  </div>
                </div>}
              </>) : <div className="wsd-empty">{busy === "load" ? "Loading…" : "No workspace data available."}</div>}
            </main>
          </div>
        </section>
      </div>
    );
  }

  function DataPane({ workspace, busy, updateWorkspace, runSync, features }) {
    const [mode, setMode] = useState(workspace.database_mode || "dedicated");
    const [shared, setShared] = useState(workspace.shared_features || []);
    const [frequency, setFrequency] = useState(workspace.sync_frequency || "manual");
    const [next, setNext] = useState(workspace.next_sync_at ? new Date(workspace.next_sync_at).toISOString().slice(0,16) : "");
    const [restore, setRestore] = useState("");
    useEffect(() => {
      setMode(workspace.database_mode || "dedicated"); setShared(workspace.shared_features || []);
      setFrequency(workspace.sync_frequency || "manual");
    }, [workspace.id, workspace.database_mode, workspace.sync_frequency]);
    const toggle = (feature) => setShared(shared.includes(feature) ? shared.filter((item) => item !== feature) : [...shared, feature]);
    return <div className="wsd-pane">
      <div className="wsd-note">Shared mode is live across locations. Hybrid mode shares only selected features. Dedicated mode remains isolated.</div>
      <div className="wsd-grid">
        <label className="wsd-field"><span>Database policy</span><select value={mode} onChange={(e) => setMode(e.target.value)}>
          <option value="dedicated">Dedicated</option><option value="shared">Shared</option><option value="hybrid">Hybrid</option></select></label>
        <label className="wsd-field"><span>Automatic sync</span><select value={frequency} onChange={(e) => setFrequency(e.target.value)}>
          <option value="manual">Manual</option><option value="daily">Daily</option><option value="weekly">Weekly</option></select></label>
        <label className="wsd-field full"><span>Next scheduled sync</span><input type="datetime-local" value={next} onChange={(e) => setNext(e.target.value)} /></label>
      </div>
      {mode === "hybrid" && <div className="wsd-feature-box"><span>Shared software features</span><div className="wsd-check-grid">
        {features.map((feature) => <label key={feature}><input type="checkbox" checked={shared.includes(feature)} onChange={() => toggle(feature)} /> {featureNames[feature] || feature}</label>)}
      </div></div>}
      <div className="wsd-actions"><button className="wsd-ghost" disabled={busy === "sync"} onClick={() => runSync()}>Sync latest data</button>
        <button className="wsd-cta" disabled={busy === "save"} onClick={() => updateWorkspace({
          database_mode:mode, shared_features:shared, sync_enabled:frequency !== "manual",
          sync_frequency:frequency, next_sync_at:next ? new Date(next).toISOString() : null,
        }, "Data sharing and synchronization settings saved.")}>Save data policy</button></div>
      <div className="wsd-restore"><div><b>90-day recovery</b><span>Restore soft-deleted shared records from a selected date, then synchronize.</span></div>
        <input type="datetime-local" min={new Date(Date.now()-90*86400000).toISOString().slice(0,16)} max={new Date().toISOString().slice(0,16)} value={restore} onChange={(e) => setRestore(e.target.value)} />
        <button className="wsd-ghost" disabled={!restore || busy === "sync"} onClick={() => runSync(restore)}>Restore & sync</button></div>
    </div>;
  }

  function BrandPane({ workspace, branding, busy, updateWorkspace }) {
    const [form, setForm] = useState({
      use_hq_branding: branding.use_hq_branding !== false,
      brand_name: branding.brand_name || workspace.name,
      logo_url: branding.logo_url || "",
      primary_color: branding.primary_color || "#1b7528",
      custom_domain: branding.custom_domain || "",
      hide_powered_by: Boolean(branding.hide_powered_by),
      email_from_name: branding.email_from_name || workspace.name,
      email_reply_to: branding.email_reply_to || "",
      email_header: branding.email_header || "",
      notification_footer: branding.notification_footer || "",
    });
    useEffect(() => setForm((current) => ({...current, ...branding})), [workspace.id]);
    const patch = (value) => setForm({...form, ...value});
    const upload = (file) => {
      if (!file) return; const reader = new FileReader();
      reader.onload = () => patch({logo_url:reader.result, use_hq_branding:false});
      reader.readAsDataURL(file);
    };
    return <div className="wsd-pane">
      <div className="wsd-note">Enterprise white-label applies live to navigation and transactional email. Custom login URLs require verified DNS before activation.</div>
      <label className="wsd-toggle"><span><b>Use headquarters branding</b><small>Keep the HQ logo and defaults across all locations</small></span>
        <input type="checkbox" checked={form.use_hq_branding} onChange={(e) => patch({use_hq_branding:e.target.checked})} /></label>
      <div className="wsd-logo-set"><span className="wsd-av lg">{form.logo_url ? <img src={form.logo_url} alt="" /> : initials(form.brand_name)}</span>
        <label className="wsd-upload">Upload separate logo<input hidden type="file" accept="image/*" onChange={(e) => upload(e.target.files[0])} /></label></div>
      <div className="wsd-grid">
        <label className="wsd-field"><span>Brand name</span><input value={form.brand_name} onChange={(e) => patch({brand_name:e.target.value})} /></label>
        <label className="wsd-field"><span>Primary color</span><input type="color" value={form.primary_color} onChange={(e) => patch({primary_color:e.target.value})} /></label>
        <label className="wsd-field full"><span>Custom login URL (DNS verification required)</span><input value={form.custom_domain} onChange={(e) => patch({custom_domain:e.target.value})} placeholder="login.company.com" /></label>
        <label className="wsd-field"><span>Email sender name</span><input value={form.email_from_name} onChange={(e) => patch({email_from_name:e.target.value})} /></label>
        <label className="wsd-field"><span>Email reply-to</span><input type="email" value={form.email_reply_to} onChange={(e) => patch({email_reply_to:e.target.value})} /></label>
        <label className="wsd-field full"><span>Email notification header</span><input value={form.email_header} onChange={(e) => patch({email_header:e.target.value})} /></label>
        <label className="wsd-field full"><span>Notification footer</span><textarea value={form.notification_footer} onChange={(e) => patch({notification_footer:e.target.value})} /></label>
      </div>
      <label className="wsd-toggle"><span>Hide “Powered by NutriDMS”</span><input type="checkbox" checked={form.hide_powered_by} onChange={(e) => patch({hide_powered_by:e.target.checked})} /></label>
      <button className="wsd-cta" disabled={busy === "save"} onClick={() => updateWorkspace({branding:form}, "White-label and email settings saved.")}>Save white-label settings</button>
    </div>;
  }

  window.WorkspaceDrawer = WorkspaceDrawer;
})();
