/* NutriDMS — unified Customer Portal workspace (screens/customer-portal-hub.jsx).
   One screen with tabs: Configure (Customer Mobile View) · Public Preview
   (QR scan flow) · Customer App (registered dashboard) · Customers (CRM).
   Collapses the 3-4 separate sidebar entries into a single coherent workspace
   so the same components + data are obviously one system. */
(function () {
  const { useState: hS } = React;
  const I = (n, s, st) => <Icon name={n} size={s || 15} stroke={st || 2} />;

  function ExpDashboard() {
    const CP = window.CustomerPortal;
    const [menuPrev, setMenuPrev] = hS(null);
    const pubMenus = (function () { try { return (window.RestaurantMenus ? window.RestaurantMenus.load() : []).filter((m) => String(m.status).toUpperCase() === "PUBLISHED"); } catch (e) { return []; } })();
    let offs = []; try { offs = (typeof ofLoad === "function") ? ofLoad() : (window.__offerings || []); } catch (e) {}
    if (!offs.length) { try { offs = (window.RECIPES || []).slice(0, 8).map((r) => ({ id: r.id, name: r.name, type: "recipe" })); } catch (e) {} }
    const rows = offs.map((o) => { const pid = CP.pubId(o.type || "item", o.id); const st = CP.itemSettings(pid); return { o, st, a: CP.analytics(pid) }; });
    const pub = rows.filter((r) => r.st.status === "published");
    const draft = rows.filter((r) => r.st.status !== "published");
    const scans = rows.reduce((s, r) => s + (r.a.scans || 0), 0);
    const KPI = [["Published", pub.length, "globe", "#1E9E62"], ["Drafts", draft.length, "file-pen", "#E0902A"], ["Total scans", scans.toLocaleString(), "scan-line", "#2E6FD6"], ["Avg rating", "4.8", "star", "#9B6BF0"]];
    const TEMPLATES = [["Restaurant menu", "Full dining experience — menu, sides, reviews, loyalty", "utensils", "restaurant"], ["Packaged product", "Nutrition, ingredients, allergens, spec sheet", "package", "packaged"], ["Meal-prep label", "Heating, storage, batch, reorder", "microwave", "mealprep"], ["Catering package", "Portions, allergen matrix, request quote", "chef-hat", "catering"]];
    const THEMES = [["Fresh (default)", "#1E9E62"], ["Midnight", "#0F172A"], ["Warm", "#E0902A"], ["Ocean", "#2E6FD6"], ["Berry", "#9B2C6F"]];
    return (
      <div className="cxd">
        <div className="cxd-kpis">{KPI.map(([l, v, ic, c]) => <div key={l} className="cxd-kpi"><span className="cxd-kpi-ic" style={{ background: c + "18", color: c }}><Icon name={ic} size={16} /></span><div><b>{v}</b><span>{l}</span></div></div>)}</div>
        <div className="cxd-cols">
          <div className="cxd-card">
            <div className="cxd-h"><Icon name="globe" size={14} /> Published experiences <span>{pub.length}</span></div>
            {pub.length ? pub.slice(0, 6).map((r) => <div key={r.o.id} className="cxd-row cxd-clk" onClick={() => { try { window.__cpConfigureItem = CP.pubId(r.o.type || "item", r.o.id); window.__cpHubSetTab && window.__cpHubSetTab("configure"); } catch (e) {} }}><span className="cxd-dot pub" /><span className="cxd-nm">{r.o.name}</span><span className="cxd-meta">{(r.a.scans || 0).toLocaleString()} scans</span><Icon name="chevron-right" size={14} /></div>) : <div className="cxd-empty">Nothing published yet.</div>}
          </div>
          <div className="cxd-card">
            <div className="cxd-h"><Icon name="file-pen" size={14} /> Drafts <span>{draft.length}</span></div>
            {draft.length ? draft.slice(0, 6).map((r) => <div key={r.o.id} className="cxd-row cxd-clk" onClick={() => { try { window.__cpConfigureItem = CP.pubId(r.o.type || "item", r.o.id); window.__cpHubSetTab && window.__cpHubSetTab("configure"); } catch (e) {} }}><span className="cxd-dot draft" /><span className="cxd-nm">{r.o.name}</span><span className="cxd-meta">v{r.st.version || 1}</span><Icon name="chevron-right" size={14} /></div>) : <div className="cxd-empty">No drafts.</div>}
          </div>
        </div>
        <div className="cxd-card">
          <div className="cxd-h"><Icon name="book-open" size={14} /> Published restaurant menus <span>{pubMenus.length}</span></div>
          {pubMenus.length
            ? pubMenus.slice(0, 6).map((m) => <div key={m.id} className="cxd-row cxd-clk" onClick={() => setMenuPrev(m)}><span className="cxd-dot pub" /><span className="cxd-nm">{m.name}</span><span className="cxd-meta">{(m.items || []).length} items</span><Icon name="smartphone" size={14} /></div>)
            : <div className="cxd-empty">No published menu yet. Build and publish one in Restaurant Menus, then it appears in the customer app.</div>}
        </div>
        <div className="cxd-card">
          <div className="cxd-h"><Icon name="layout-template" size={14} /> Templates</div>
          <div className="cxd-tpl-grid">{TEMPLATES.map(([t, d, ic, ty]) => <button key={t} className="cxd-tpl" onClick={() => { try { window.__cpTemplate = ty; window.__cpConfigureItem = null; window.__cpHubSetTab && window.__cpHubSetTab("configure"); window.__toast && window.__toast("Starting a " + t + " experience"); } catch (e) {} }}><span className="cxd-tpl-ic"><Icon name={ic} size={16} /></span><b>{t}</b><span>{d}</span></button>)}</div>
        </div>
        <div className="cxd-card">
          <div className="cxd-h"><Icon name="palette" size={14} /> Themes</div>
          <div className="cxd-themes">{THEMES.map(([t, c]) => <button key={t} className="cxd-theme" onClick={() => { try { CP.setOrg({ brand: c }); window.__toast && window.__toast(t + " theme applied"); } catch (e) {} }}><span className="cxd-theme-sw" style={{ background: c }} />{t}</button>)}</div>
        </div>
        {menuPrev && window.RmMobilePreview && React.createElement(window.RmMobilePreview, { menu: menuPrev, onClose: () => setMenuPrev(null) })}
      </div>
    );
  }
  window.CustomerExpDashboard = ExpDashboard;

  function CustomerPortalHub() {
    const initial0 = (window.__cpHubTab) || "dashboard";
    const [tab, setTab] = hS(initial0);
    React.useEffect(() => { window.__cpHubSetTab = setTab; return () => { window.__cpHubSetTab = null; }; }, []);
    const ce = window.CustomerEngagement;
    const plan = (window.orgPlan ? window.orgPlan() : "professional");
    if (ce && !ce.available()) {
      const price = ce.addonPrice(plan);
      const canBuy = window.__role === "admin" || window.__role === "super-admin";
      return (
        <div className="cph">
          <div className="cph-head"><div className="cph-title"><h1 className="page-title">Customer Digital Experience</h1><p className="page-sub">Turn your products and menus into interactive customer experiences.</p></div></div>
          <div className="cph-upgrade">
            <div className="cph-up-ic">{I("smartphone", 30, 1.8)}</div>
            <h2>Activate the Customer Experience add-on</h2>
            <p>Public QR pages, today's menu, nutrition & allergen display, loyalty, reviews and customer CRM — connected live to your published offerings.</p>
            <div className="cph-up-prices">
              <div className={"cph-up-price" + (plan === "starter" ? " on" : "")}><b>$120</b><span>/mo</span><em>Starter add-on</em></div>
              <div className={"cph-up-price" + (plan === "professional" || plan === "business" ? " on" : "")}><b>$55</b><span>/mo</span><em>Professional add-on</em></div>
              <div className={"cph-up-price incl" + (plan === "enterprise" ? " on" : "")}><b>Included</b><em>Enterprise</em></div>
            </div>
            <div className="cph-up-btns">
              {canBuy
                ? <button className="btn primary" onClick={() => { ce.setAddonPurchased(true); try { window.dispatchEvent(new Event("nutridms-nav")); window.__toast && window.__toast("Customer Experience add-on activated"); } catch (e) {} setTab("configure"); }}><Icon name="check" size={15} /> Activate add-on{ce.addonPrice(plan) > 0 ? ` · $${ce.addonPrice(plan)}/mo` : ""}</button>
                : <button className="btn primary" disabled title="Ask an admin to activate">Ask an admin to activate</button>}
              <button className="btn secondary" onClick={() => { try { window.__setPage && window.__setPage("settings"); } catch (e) {} }}>Manage in Settings</button>
            </div>
          </div>
        </div>
      );
    }
    const initial = (window.__cpHubTab) || "dashboard";
    window.__cpHubTab = null;
    const TABS = [
      ["dashboard", "Overview", "layout-dashboard", "CustomerExpDashboard"],
      ["configure", "Experience Settings", "sliders-horizontal", "CustomerMobileView"],
      ["preview", "Mobile Preview", "qr-code", "CustomerQR"],
      ["app", "Customer Account", "smartphone", "CustomerDashboard"],
      ["crm", "Customers", "users", "CustomerCRM"],
    ];
    const active = TABS.find((t) => t[0] === tab) || TABS[0];
    const Comp = window[active[3]];
    return (
      <div className="cph">
        <div className="cph-head">
          <div className="cph-title"><h1 className="page-title">Customer Experience</h1><p className="page-sub">Controls how your published menu appears to customers. Menu items, pricing, nutrition, allergens and availability are managed in Menu Builder.</p></div>
          <div className="cph-tabs">{TABS.map(([id, l, ic]) => <button key={id} className={"cph-tab" + (tab === id ? " on" : "")} onClick={() => setTab(id)}>{I(ic, 15)} {l}</button>)}
            <button className="cph-tab cph-mb" onClick={() => { try { window.__setPage && window.__setPage("restaurant-menus"); } catch (e) {} }}>{I("book-open", 15)} Open Menu Builder</button>
          </div>
        </div>
        <div className="cph-flow">{I("arrow-right", 12)} <span>Scan QR code → Browse the published menu → Select a meal → Customize &amp; review nutrition → Continue to order → Sign in optionally for loyalty &amp; saved preferences. Menu built in <b className="cph-link" onClick={() => { try { window.__setPage && window.__setPage("restaurant-menus"); } catch (e) {} }}>Menu Builder</b>.</span></div>
        <div className="cph-body">{Comp ? React.createElement(Comp) : <div className="empty">Module not loaded.</div>}</div>
      </div>
    );
  }
  window.CustomerPortalHub = CustomerPortalHub;
})();
