/* page-automations.jsx — Automations module (Config section, B-AUTO). IIFE-scoped; exports via window.
 * Zapier-style WHEN → THEN rules. GA authors (automation.create/.delete = [GA]); CM/AM/OM view
 * within their scope, read-only. Single list page + read|edit|create DetailDrawer (Ops-drawer pattern,
 * §35). Account-created triggers carry a unique sign-up QR (canonical <QrPanel>).
 *
 * Deps: helpers.jsx — _hasRbac, _canDelete, _go, _notAuthorised, _fmtDateTime, T_MUTED
 *       mock-data.js — AUTOMATIONS, SB4_REWARDS, GIFT_ITEMS, CUSTOM_OPTIONS (loyalty_tier),
 *                      SB3_AREAS, SB3_OUTLETS, SB2_COUNTRIES, SB2_COUNTRY_BY_ID
 *       shared-blocks.jsx — QrPanel, StatusPill kind "automation" (active / disabled)
 */
(function(){
const { useState, useMemo } = React;

// ── Cross-module global readers (guard every read) ──
const _automations  = () => (typeof AUTOMATIONS !== "undefined") ? AUTOMATIONS : (window.AUTOMATIONS || []);
const _rewardsArr   = () => (typeof SB4_REWARDS !== "undefined") ? SB4_REWARDS : (window.SB4_REWARDS || []);
const _giftItems    = () => (typeof GIFT_ITEMS !== "undefined") ? GIFT_ITEMS : (window.GIFT_ITEMS || []);
const _customOpts   = () => (typeof CUSTOM_OPTIONS !== "undefined") ? CUSTOM_OPTIONS : (window.CUSTOM_OPTIONS || []);
const _areasArr     = () => (typeof SB3_AREAS !== "undefined") ? SB3_AREAS : (window.SB3_AREAS || []);
const _outletsArr   = () => (typeof SB3_OUTLETS !== "undefined") ? SB3_OUTLETS : (window.SB3_OUTLETS || []);
const _countriesArr = () => (typeof SB2_COUNTRIES !== "undefined") ? SB2_COUNTRIES : (window.SB2_COUNTRIES || []);
const _countryById  = () => (typeof SB2_COUNTRY_BY_ID !== "undefined") ? SB2_COUNTRY_BY_ID : (window.SB2_COUNTRY_BY_ID || {});

const _flagOf = (cid) => (_countryById()[cid] || {}).flag || "🏳️";
const _countryName = (cid) => (_countryById()[cid] || {}).country_name || cid;
const _areaName = (aid) => { const a = _areasArr().find(x => x.id === aid); return a ? a.name : aid; };
const _outletName = (oid) => { const o = _outletsArr().find(x => x.id === oid); return o ? o.location : oid; };
const _rewardName = (rid) => { const r = _rewardsArr().find(x => x.id === rid); return r ? r.name : "—"; };
const _giftName = (gid) => { const g = _giftItems().find(x => x.id === gid); return g ? g.name : "—"; };
const _tierOpts = () => _customOpts().filter(o => o.option_type === "loyalty_tier" && o.scope === "ALL").map(o => ({ value: o.label, label: o.label }));

// ── Enum option lists ──
const TRIGGER_OPTS = [
  { value: "account_created",    label: "New account created" },
  { value: "loyalty_threshold",  label: "Loyalty points reached" },
  { value: "purchase_frequency", label: "Purchase frequency" },
];
const ACTION_OPTS = [
  { value: "reward",      label: "Issue reward" },
  { value: "gift",        label: "Send gift" },
  { value: "discount",    label: "Apply POS discount" },
  { value: "tier_change", label: "Change loyalty tier" },
];
const STATUS_FILTER_OPTS = [
  { value: "",         label: "All statuses" },
  { value: "active",   label: "Active" },
  { value: "disabled", label: "Disabled" },
];
const STATUS_FORM_OPTS = [
  { value: "active",   label: "Active" },
  { value: "disabled", label: "Disabled" },
];
const TRIGGER_FILTER_OPTS = [{ value: "", label: "All triggers" }, ...TRIGGER_OPTS];
const WINDOW_OPTS = [{ value: "week", label: "week" }, { value: "month", label: "month" }];
const DISCOUNT_KIND_OPTS = [{ value: "percent", label: "Percentage" }, { value: "fixed", label: "Fixed amount" }];

const _label = (opts, v) => { const o = opts.find(x => x.value === v); return o ? o.label : v; };

// ── Human-readable summaries (the When / Then plain-language lines) ──
const triggerSummary = (a) => {
  if (a.trigger_type === "account_created")    return "New account via sign-up QR code";
  if (a.trigger_type === "loyalty_threshold")  return `Reaches ${Number(a.trigger_config?.points || 0).toLocaleString()} loyalty points`;
  if (a.trigger_type === "purchase_frequency") return `${a.trigger_config?.count || 0} purchases in a ${a.trigger_config?.window || "week"}`;
  return "—";
};
const actionSummary = (a) => {
  const c = a.action_config || {};
  if (a.action_type === "reward")      return `Issue reward — ${_rewardName(c.reward_id)}`;
  if (a.action_type === "gift")        return `Send gift — ${_giftName(c.gift_item_id)}`;
  if (a.action_type === "discount")    return c.kind === "percent" ? `${c.value || 0}% POS discount` : `${c.value || 0} POS discount (fixed)`;
  if (a.action_type === "tier_change") return `Upgrade loyalty tier to ${c.tier_label || "—"}`;
  return "—";
};
const scopeSummary = (a) => {
  const bits = [`${_flagOf(a.country_id)} ${_countryName(a.country_id)}`];
  if (a.area_id) bits.push(_areaName(a.area_id));
  if (a.outlet_ids && a.outlet_ids.length) bits.push(a.outlet_ids.length === 1 ? _outletName(a.outlet_ids[0]) : `${a.outlet_ids.length} outlets`);
  return bits.join(" · ");
};

// ── empty draft for create ──
const _emptyAutomation = (scopeCountry) => ({
  id: null, name: "", status: "active",
  country_id: scopeCountry || "PH", area_id: "", outlet_ids: [],
  trigger_type: "account_created", trigger_config: {},
  action_type: "reward", action_config: { reward_id: "" },
  qr_code: null,
});

// ── default action_config when the action type changes ──
const _defaultActionConfig = (type) => {
  if (type === "reward")      return { reward_id: "" };
  if (type === "gift")        return { gift_item_id: "" };
  if (type === "discount")    return { kind: "percent", value: "" };
  if (type === "tier_change") return { tier_label: "" };
  return {};
};
const _defaultTriggerConfig = (type) => {
  if (type === "loyalty_threshold")  return { points: "" };
  if (type === "purchase_frequency") return { count: "", window: "week" };
  return {};
};

/**
 * @spec B-AUTO — Automations (Config section, role-parameterised)
 * GA authors WHEN→THEN automation rules; CM/AM/OM view within scope (read-only).
 */
function AutomationsList({ role = "GA", scope = {} }) {
  if (!["GA", "CM", "AM", "OM"].includes(role)) return _notAuthorised;

  const isGA = role === "GA";
  const scopeCountry = scope && scope.countryId ? scope.countryId : "PH";
  const canManage = _hasRbac(role, "automation.create"); // GA only
  const canDelete = _hasRbac(role, "automation.delete"); // GA only

  // ── mutable store ──
  const [items, setItems] = useState(() => _automations().map(a => ({ ...a })));

  // ── filter + pagination state ──
  const [searchQuery, setSearchQuery] = useState("");
  const [filters, setFilters] = useState({});
  const [advFilters, setAdvFilters] = useState({});
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);

  // ── drawer + modal state ──
  const [drawerFor, setDrawerFor] = useState(null);
  const [mode, setMode] = useState("read"); // read | edit | create
  const [draft, setDraft] = useState(null);
  const [toast, setToast] = useState(null);
  const fireToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 2400); };

  // ── row scope (mirrors InboxPage scope narrowing) ──
  const scopedItems = useMemo(() => {
    if (isGA) return items;
    if (role === "CM") return items.filter(a => a.country_id === scope.countryId);
    if (role === "AM") return items.filter(a => a.country_id === scope.countryId && (!a.area_id || a.area_id === scope.areaId));
    // OM — automations covering their outlet: explicitly listed, or scope-wide within their area/country
    return items.filter(a => a.country_id === scope.countryId
      && ((a.outlet_ids && a.outlet_ids.includes(scope.outletId))
        || ((!a.outlet_ids || a.outlet_ids.length === 0) && (!a.area_id || a.area_id === scope.areaId))));
  }, [items, role, scope.countryId, scope.areaId, scope.outletId]);

  // ── filtered rows ──
  const rows = useMemo(() => {
    let r = scopedItems;
    if (searchQuery) { const q = searchQuery.toLowerCase(); r = r.filter(a => (a.name || "").toLowerCase().includes(q)); }
    if (filters.status)       r = r.filter(a => a.status === filters.status);
    if (filters.trigger_type) r = r.filter(a => a.trigger_type === filters.trigger_type);
    if (advFilters.geo) {
      const { countries: gc } = advFilters.geo || {};
      if (gc && gc.length > 0) r = r.filter(a => gc.includes(a.country_id));
    }
    return r;
  }, [scopedItems, searchQuery, filters, advFilters]);

  const totalPages = Math.max(1, Math.ceil(rows.length / pageSize));
  const visibleRows = rows.slice((page - 1) * pageSize, page * pageSize);

  // ── drawer helpers ──
  const drawerRow = drawerFor ? items.find(a => a.id === drawerFor) || null : null;
  const isCreate = mode === "create";
  const isEdit = mode === "edit";
  const isForm = isEdit || isCreate;

  const openRead = (row) => { setDrawerFor(row.id); setMode("read"); setDraft(null); };
  const closeDrawer = () => { setDrawerFor(null); setMode("read"); setDraft(null); };
  const startEdit = () => { setDraft({ ...drawerRow }); setMode("edit"); };
  const startCreate = () => { setDrawerFor(null); setDraft(_emptyAutomation(scopeCountry)); setMode("create"); };
  const setD = (k, v) => setDraft(d => ({ ...d, [k]: v }));
  const setTC = (k, v) => setDraft(d => ({ ...d, trigger_config: { ...d.trigger_config, [k]: v } }));
  const setAC = (k, v) => setDraft(d => ({ ...d, action_config: { ...d.action_config, [k]: v } }));

  // ── scope cascade options (form) ──
  const countryOpts = useMemo(() => _countriesArr().map(c => ({ value: c.country_id, label: `${c.flag} ${c.country_name}` })), []);
  const areaOpts = useMemo(() => {
    if (!draft) return [];
    return [{ value: "", label: "All areas" },
      ..._areasArr().filter(a => a.country_id === draft.country_id).map(a => ({ value: a.id, label: a.name }))];
  }, [draft && draft.country_id]);
  const outletOpts = useMemo(() => {
    if (!draft) return [];
    const pool = _outletsArr().filter(o => o.country_id === draft.country_id && (!draft.area_id || o.area_id === draft.area_id));
    return [{ value: "", label: "All outlets" }, ...pool.map(o => ({ value: o.id, label: o.location }))];
  }, [draft && draft.country_id, draft && draft.area_id]);
  const rewardOpts = useMemo(() => [{ value: "", label: "Choose reward" },
    ..._rewardsArr().filter(r => !draft || (r.country_eligible && r.country_eligible[draft.country_id])).map(r => ({ value: r.id, label: r.name }))], [draft && draft.country_id]);
  const giftOpts = useMemo(() => [{ value: "", label: "Choose gift" },
    ..._giftItems().filter(g => !draft || g.country_id === draft.country_id).map(g => ({ value: g.id, label: g.name }))], [draft && draft.country_id]);

  // ── change-handlers that reset dependent config ──
  const onTriggerType = (v) => setDraft(d => ({ ...d, trigger_type: v, trigger_config: _defaultTriggerConfig(v), qr_code: v === "account_created" ? d.qr_code : null }));
  const onActionType = (v) => setDraft(d => ({ ...d, action_type: v, action_config: _defaultActionConfig(v) }));
  const onCountry = (v) => setDraft(d => ({ ...d, country_id: v, area_id: "", outlet_ids: [] }));
  const onArea = (v) => setDraft(d => ({ ...d, area_id: v, outlet_ids: [] }));
  const onOutlet = (v) => setDraft(d => ({ ...d, outlet_ids: v ? [v] : [] }));

  // ── save ──
  const saveForm = () => {
    if (!draft || !draft.name.trim()) return;
    const rec = { ...draft, area_id: draft.area_id || null };
    if (isCreate) {
      const id = `au_NEW_${Date.now()}`;
      rec.id = id;
      if (rec.trigger_type === "account_created" && !rec.qr_code) rec.qr_code = `6h.app/j/${id}`;
      rec.created_at = new Date().toISOString();
      rec.created_by_name = "You";
      setItems(ps => [rec, ...ps]);
      setDrawerFor(id);
      fireToast("Automation created");
    } else {
      if (rec.trigger_type === "account_created" && !rec.qr_code) rec.qr_code = `6h.app/j/${rec.id}`;
      if (rec.trigger_type !== "account_created") rec.qr_code = null;
      setItems(ps => ps.map(a => a.id === rec.id ? { ...a, ...rec } : a));
      fireToast("Automation saved");
    }
    setMode("read");
    setDraft(null);
  };

  // ── per-role description ──
  const desc = isGA ? "Configure “when this, then give that” reward, gift, discount and tier rules."
    : "Automations active in your scope (read-only).";

  // ── filter config ──
  const primaryFilter = [
    { key: "status",       label: "Status",  options: STATUS_FILTER_OPTS },
    { key: "trigger_type", label: "Trigger", options: TRIGGER_FILTER_OPTS },
  ];
  const advancedFilters = isGA ? [
    { key: "geo", kind: "geoscope", label: "Network scope", role,
      countries: _countriesArr().map(c => ({ value: c.country_id, label: `${c.flag} ${c.country_name}` })),
      areas: _areasArr().map(a => ({ value: a.id, label: a.name, country_id: a.country_id })),
      outlets: _outletsArr().map(o => ({ value: o.id, label: o.location, area_id: o.area_id })) },
  ] : [];

  // ── columns ──
  const colChevron = { label: "", width: 36, render: () => <span style={{ color: "var(--forest)" }}>{Ic.chevR(16)}</span> };
  const columns = [
    { label: "Name",   sortable: true, sortKey: "name", render: a => <span style={{ ...T.primary() }}>{a.name}</span> },
    { label: "When",   width: 220, sortable: true, sortKey: "trigger_type", render: a => <span style={T_MUTED}>{triggerSummary(a)}</span> },
    { label: "Then",   width: 220, sortable: true, sortKey: "action_type", render: a => <span style={T_MUTED}>{actionSummary(a)}</span> },
    { label: "Scope",  width: 180, sortable: true, sortKey: "country_id", render: a => <span style={T_MUTED}>{scopeSummary(a)}</span> },
    { label: "Status", width: 110, sortable: true, sortKey: "status", render: a => <StatusPill status={a.status} kind="automation"/> },
    colChevron,
  ];

  // ── form (create + edit) ──
  const formContent = draft && (
    <>
      <FormSection title="General">
        <Field label="Name" required hint="A clear name, e.g. “Welcome reward — Metro Manila”.">
          <Input value={draft.name} onChange={v => setD("name", v)} placeholder="Name this automation"/>
        </Field>
        <Field label="Status">
          <Select value={draft.status} onChange={v => setD("status", v)} options={STATUS_FORM_OPTS}/>
        </Field>
      </FormSection>

      <FormSection title="Scope" description="Where this automation applies. Leave area or outlet unset to cover the whole country.">
        <Field label="Country" required>
          <Select value={draft.country_id} onChange={onCountry} options={countryOpts}/>
        </Field>
        <Field label="Area">
          <Select value={draft.area_id || ""} onChange={onArea} options={areaOpts}/>
        </Field>
        <Field label="Outlet">
          <Select value={(draft.outlet_ids && draft.outlet_ids[0]) || ""} onChange={onOutlet} options={outletOpts}/>
        </Field>
      </FormSection>

      <FormSection title="When (trigger)">
        <Field label="Trigger" required>
          <Select value={draft.trigger_type} onChange={onTriggerType} options={TRIGGER_OPTS}/>
        </Field>
        {draft.trigger_type === "account_created" && draft.qr_code && (
          <Field label="Sign-up QR code" hint="Customers who register through this code are matched to the scope above.">
            <QrPanel code={draft.qr_code}
              onDownload={() => fireToast("QR code downloaded")}
              onRegenerate={() => setDraft(d => ({ ...d, qr_code: `6h.app/j/${d.id || "new"}-${Date.now().toString().slice(-4)}` }))}/>
          </Field>
        )}
        {draft.trigger_type === "account_created" && !draft.qr_code && (
          <InlineAlert kind="info">A unique sign-up QR code is generated when you save. Customers who register through it are matched to the scope above.</InlineAlert>
        )}
        {draft.trigger_type === "loyalty_threshold" && (
          <Field label="Loyalty points" required hint="Accumulative points earned (redemptions don’t reduce the trigger).">
            <Input type="number" value={draft.trigger_config.points || ""} onChange={v => setTC("points", v)} placeholder="e.g. 1500"/>
          </Field>
        )}
        {draft.trigger_type === "purchase_frequency" && (
          <>
            <Field label="Number of purchases" required>
              <Input type="number" value={draft.trigger_config.count || ""} onChange={v => setTC("count", v)} placeholder="e.g. 3"/>
            </Field>
            <Field label="Within">
              <Select value={draft.trigger_config.window || "week"} onChange={v => setTC("window", v)} options={WINDOW_OPTS}/>
            </Field>
          </>
        )}
      </FormSection>

      <FormSection title="Then (action)">
        <Field label="Action" required>
          <Select value={draft.action_type} onChange={onActionType} options={ACTION_OPTS}/>
        </Field>
        {draft.action_type === "reward" && (
          <Field label="Reward" required>
            <Select value={draft.action_config.reward_id || ""} onChange={v => setAC("reward_id", v)} options={rewardOpts}/>
          </Field>
        )}
        {draft.action_type === "gift" && (
          <Field label="Gift" required>
            <Select value={draft.action_config.gift_item_id || ""} onChange={v => setAC("gift_item_id", v)} options={giftOpts}/>
          </Field>
        )}
        {draft.action_type === "discount" && (
          <>
            <Field label="Discount type" required>
              <Select value={draft.action_config.kind || "percent"} onChange={v => setAC("kind", v)} options={DISCOUNT_KIND_OPTS}/>
            </Field>
            <Field label={draft.action_config.kind === "fixed" ? "Amount" : "Percentage"} required>
              <Input type="number" value={draft.action_config.value || ""} onChange={v => setAC("value", v)} placeholder={draft.action_config.kind === "fixed" ? "e.g. 50" : "e.g. 15"}/>
            </Field>
          </>
        )}
        {draft.action_type === "tier_change" && (
          <Field label="Target tier" required>
            <Select value={draft.action_config.tier_label || ""} onChange={v => setAC("tier_label", v)}
              options={[{ value: "", label: "Choose tier" }, ..._tierOpts()]}/>
          </Field>
        )}
      </FormSection>
    </>
  );

  // ── read mode ──
  const readContent = !isForm && drawerRow && (() => {
    const a = drawerRow;
    return (
      <>
        <FormSection title="General">
          <KeyValueGrid items={[
            { label: "Name",   value: a.name },
            { label: "Status", value: <StatusPill status={a.status} kind="automation"/> },
          ]}/>
        </FormSection>

        <FormSection title="Scope">
          <KeyValueGrid items={[
            { label: "Country", value: <CountryChip flag={_flagOf(a.country_id)} code={a.country_id}/> },
            { label: "Area",    value: a.area_id ? _areaName(a.area_id) : "All areas" },
            { label: "Outlet",  value: (a.outlet_ids && a.outlet_ids.length) ? a.outlet_ids.map(_outletName).join(", ") : "All outlets" },
          ]}/>
        </FormSection>

        <FormSection title="When (trigger)">
          <KeyValueGrid items={[{ label: "Condition", value: triggerSummary(a) }]}/>
        </FormSection>

        <FormSection title="Then (action)">
          <KeyValueGrid items={[{ label: "Outcome", value: actionSummary(a) }]}/>
        </FormSection>

        {a.trigger_type === "account_created" && a.qr_code && (
          <FormSection title="Sign-up QR code">
            <QrPanel code={a.qr_code}
              onDownload={() => fireToast("QR code downloaded")}
              onRegenerate={() => fireToast("QR code regenerated")}/>
          </FormSection>
        )}

        <FormSection title="Activity">
          <KeyValueGrid items={[
            { label: "Created",    value: _fmtDateTime(a.created_at, a.country_id) },
            { label: "Created by", value: a.created_by_name || "—" },
          ]}/>
        </FormSection>

        {canDelete && (
          <DeleteSection
            entityLabel="automation"
            soft={a.status !== "draft"}
            note="Decommission (soft-delete) this automation. It stops firing immediately. GA-only."
            gate={_canDelete(role, { status: a.status, isReferenced: false, rbacOk: canDelete })}
            confirmBody={<div>Delete <strong>{a.name}</strong>? It will stop firing and is written to <strong>audit_logs</strong>.</div>}
            onDelete={() => { setItems(ps => ps.filter(x => x.id !== a.id)); closeDrawer(); }}
          />
        )}
      </>
    );
  })();

  // ── drawer actions ──
  const drawerActions = isForm ? (
    <>
      <Btn variant="secondary" onClick={() => { if (isCreate) closeDrawer(); else { setMode("read"); setDraft(null); } }}>Cancel</Btn>
      <Btn variant="primary" onClick={saveForm} disabled={!draft || !draft.name.trim()}>
        {isCreate ? "Create automation" : "Save"}
      </Btn>
    </>
  ) : (
    <>
      <Btn variant="secondary" onClick={closeDrawer}>Close</Btn>
      {canManage && drawerRow && <Btn variant="primary" onClick={startEdit}>Edit</Btn>}
    </>
  );

  const drawerTitle = isCreate ? "New automation" : (drawerRow ? drawerRow.name : "");

  return (
    <div className="page-inner">
      <PageHead
        title="Automations"
        description={desc}
        actions={
          <>
            <ExportButton role={role} onClick={() => fireToast("Exporting automations…")}/>
            {canManage && <Btn variant="primary" onClick={startCreate}>New automation</Btn>}
          </>
        }
      />

      <FilterBar
        primaryFilter={primaryFilter}
        primaryValue={filters}
        onPrimaryChange={next => { setFilters(f => ({ ...f, ...next })); setPage(1); }}
        advancedFilters={advancedFilters}
        advancedValues={advFilters}
        onAdvancedChange={(k, v) => { setAdvFilters(f => ({ ...f, [k]: v })); setPage(1); }}
        onAdvancedReset={() => { setAdvFilters({}); setPage(1); }}
        onReset={() => { setFilters({}); setAdvFilters({}); setSearchQuery(""); setPage(1); }}
        search={searchQuery}
        onSearch={q => { setSearchQuery(q); setPage(1); }}
        searchPlaceholder="Search automations…"
      />

      <Table
        columns={columns}
        rows={visibleRows}
        onRow={openRead}
        emptyText="No automations match these filters."
      />

      <TableFooter
        page={page}
        totalPages={totalPages}
        onPage={setPage}
        count={pageSize}
        onCountChange={c => { setPageSize(c); setPage(1); }}
      />

      <DetailDrawer
        open={isCreate || !!drawerFor}
        onClose={closeDrawer}
        title={drawerTitle}
        actions={drawerActions}
        width={700}
      >
        {isForm && formContent}
        {!isForm && drawerFor && readContent}
      </DetailDrawer>

      {toast && <Toast message={toast}/>}
    </div>
  );
}

Object.assign(window, { AutomationsList });
})();
