/* page-custom-options.jsx — Custom Options (B-7, GA-only, Config section).
   Single GA settings page: a scope selector (All countries / each country) at the
   top, then one ListEditor section per managed option type + a scalar editor for
   loyalty_conversion_rate. Country scope shows inherited "All countries" entries
   read-only with an Override affordance; "All countries" scope edits the source.
   IIFE-wrapped — exports via Object.assign(window, { CustomOptions }). */
(function () {
  const { useState, useMemo } = React;

  // Option-type → ListEditor field schema (kind ∈ text | number | time | toggle).
  const FIELDS = {
    concept:           [{ key: "label", label: "Label", kind: "text" }],
    outlet_size:       [{ key: "label", label: "Label", kind: "text" },
                        { key: "sqft_min", label: "Min sqft", kind: "number" },
                        { key: "sqft_max", label: "Max sqft", kind: "number" }],
    gift_type:         [{ key: "label", label: "Label", kind: "text" }],
    refund_reason_tag: [{ key: "label", label: "Label", kind: "text" },
                        { key: "requires_remark", label: "Requires remark", kind: "toggle" }],
    time_of_day_range: [{ key: "label", label: "Label", kind: "text" },
                        { key: "start", label: "Start", kind: "time" },
                        { key: "end",   label: "End",   kind: "time" }],
    loyalty_tier:      [{ key: "label", label: "Tier", kind: "text" },
                        { key: "min_points", label: "Min points", kind: "number" }],
    promo_type:        [{ key: "label", label: "Label", kind: "text" }],
    discount_type:     [{ key: "label", label: "Label", kind: "text" }],
  };

  // List sections in display order; scalar handled separately.
  const SECTIONS = [
    { type: "concept",           title: "Concepts",            cap: 5, addLabel: "Add concept" },
    { type: "outlet_size",       title: "Outlet sizes",        addLabel: "Add size band" },
    { type: "gift_type",         title: "Gift types",          addLabel: "Add gift type" },
    { type: "refund_reason_tag", title: "Refund reason tags",  addLabel: "Add reason tag" },
    { type: "time_of_day_range", title: "Time-of-day ranges",  addLabel: "Add range" },
    { type: "loyalty_tier",      title: "Loyalty tiers",       addLabel: "Add tier" },
    { type: "promo_type",        title: "Promotion types",     addLabel: "Add promo type" },
    { type: "discount_type",     title: "Discount types",      addLabel: "Add discount type" },
  ];

  let _seq = 0;
  const _newId = () => `co-new-${Date.now()}-${_seq++}`;

  /**
   * @spec B-7 — Custom Options
   * US-092. GA-managed per-market lists + loyalty config; scoped country-or-all.
   */
  function CustomOptions({ role = "GA" }) {
    if (role !== "GA") return _notAuthorised;

    const [scope, setScope] = useState("ALL");          // "ALL" | country_id
    const [entries, setEntries] = useState(() => CUSTOM_OPTIONS.map(e => ({ ...e })));

    const countries = SB2_COUNTRIES;
    const currency = scope === "ALL"
      ? "local currency"
      : (SB2_COUNTRY_BY_ID[scope]?.currency_code || "local currency");

    // ── resolution: build the rows ListEditor renders for one option type ──
    // ALL scope → all global entries, directly editable.
    // Country scope → country-specific entries (editable) + global entries shown
    //   read-only ("inherited") UNLESS a country entry already overrides them.
    const rowsFor = (type) => {
      const ofType = entries.filter(e => e.option_type === type);
      if (scope === "ALL") {
        return ofType.filter(e => e.scope === "ALL").map(e => ({ ...e }));
      }
      const countryRows = ofType.filter(e => e.scope === scope);
      const overridden = new Set(countryRows.map(e => e.overrides).filter(Boolean));
      const inherited = ofType
        .filter(e => e.scope === "ALL" && !overridden.has(e.id))
        .map(e => ({ ...e, inherited: true }));
      return [...inherited, ...countryRows];
    };

    // ── list handlers ──
    const onChange = (rowId, key, value) => setEntries(prev =>
      prev.map(e => e.id === rowId ? { ...e, [key]: value } : e));

    const onRemove = (rowId) => setEntries(prev => prev.filter(e => e.id !== rowId));

    const onAdd = (type) => setEntries(prev => {
      const base = { id: _newId(), option_type: type, scope, label: "" };
      if (type === "outlet_size")        Object.assign(base, { sqft_min: "", sqft_max: "" });
      if (type === "refund_reason_tag")  Object.assign(base, { requires_remark: false });
      if (type === "time_of_day_range")  Object.assign(base, { start: "", end: "" });
      if (type === "loyalty_tier")       Object.assign(base, { min_points: "" });
      return [...prev, base];
    });

    // Override an inherited global → country-specific editable copy linked to it.
    const onOverride = (globalId) => setEntries(prev => {
      const g = prev.find(e => e.id === globalId);
      if (!g) return prev;
      const { id, scope: _s, inherited, ...rest } = g;
      return [...prev, { ...rest, id: _newId(), scope, overrides: globalId }];
    });

    // ── scalar: loyalty_conversion_rate (one entry per scope) ──
    const scalarEntries = entries.filter(e => e.option_type === "loyalty_conversion_rate");
    const countryRate = scope === "ALL" ? null : scalarEntries.find(e => e.scope === scope);
    const globalRate  = scalarEntries.find(e => e.scope === "ALL");
    const scalarEntry = scope === "ALL" ? globalRate : (countryRate || globalRate);
    const scalarInherited = scope !== "ALL" && !countryRate;

    const onScalarChange = (v) => {
      if (!scalarEntry) return;
      setEntries(prev => prev.map(e => e.id === scalarEntry.id ? { ...e, points_per_currency: v } : e));
    };
    const onScalarOverride = () => setEntries(prev => {
      if (!globalRate) return prev;
      const { id, scope: _s, ...rest } = globalRate;
      return [...prev, { ...rest, id: _newId(), scope, overrides: globalRate.id }];
    });

    // ── scalar: inactive_threshold_days (one int per scope) — mirrors loyalty_conversion_rate ──
    const inactiveEntries = entries.filter(e => e.option_type === "inactive_threshold_days");
    const countryInactive = scope === "ALL" ? null : inactiveEntries.find(e => e.scope === scope);
    const globalInactive  = inactiveEntries.find(e => e.scope === "ALL");
    const inactiveEntry   = scope === "ALL" ? globalInactive : (countryInactive || globalInactive);
    const inactiveInherited = scope !== "ALL" && !countryInactive;

    const onInactiveChange = (v) => {
      if (!inactiveEntry) return;
      setEntries(prev => prev.map(e => e.id === inactiveEntry.id ? { ...e, days: v } : e));
    };
    const onInactiveOverride = () => setEntries(prev => {
      if (!globalInactive) return prev;
      const { id, scope: _s, ...rest } = globalInactive;
      return [...prev, { ...rest, id: _newId(), scope, overrides: globalInactive.id }];
    });

    // ── scalar: hq_timezone — one global value (GA/HQ default tz); editable at ALL scope only ──
    const hqTzEntry = entries.find(e => e.option_type === "hq_timezone" && e.scope === "ALL");
    const onHqTzChange = (v) => setEntries(prev => prev.map(e => (hqTzEntry && e.id === hqTzEntry.id) ? { ...e, tz: v } : e));
    const tzOptions = countries.map(c => ({ value: c.country_id, label: `${c.flag} ${c.country_name}` }));

    const scopeOptions = useMemo(() => ([
      { value: "ALL", label: "All countries (global default)" },
      ...countries.map(c => ({ value: c.country_id, label: `${c.flag} ${c.country_name}` })),
    ]), [countries]);

    return (
      <div className="page-inner">
        <PageHead title="Custom Options" description="Outlet-level menu add-ons and modifiers."/>

        <FormSection
          title="Scope"
          description="Choose whose configuration to view and edit. A country entry overrides the global default."
        >
          <div style={{ maxWidth: 360 }}>
            <Field label="Scope">
              <Select value={scope} onChange={setScope} options={scopeOptions} />
            </Field>
          </div>
        </FormSection>

        {SECTIONS.map(s => (
          <React.Fragment key={s.type}>
            <ListEditor
              title={s.title}
              rows={rowsFor(s.type)}
              fields={FIELDS[s.type]}
              cap={s.cap}
              addLabel={s.addLabel}
              onAdd={() => onAdd(s.type)}
              onChange={onChange}
              onRemove={onRemove}
              onOverride={onOverride}
            />
            {/* gift_type annotation — one terse line (ListEditor has no description slot) */}
            {s.type === "gift_type" && (
              <div style={{ ...T_MUTED, marginTop: -16 }}>
                Note: the Vouchers gift type issues a voucher code on purchase.
              </div>
            )}
          </React.Fragment>
        ))}

        {/* scalar — loyalty conversion rate (single value; mirrors the 1-column list layout) */}
        <section className="list-editor">
          <div className="list-editor-head">
            <div className="list-editor-title">Loyalty conversion rate</div>
          </div>
          <div className="list-editor-table">
            <div className="le-head">
              <div className="le-row-fields">
                <div className="le-col-label">{`Points per 1 ${currency}`}</div>
              </div>
              <div className="le-head-spacer" aria-hidden="true"/>
            </div>
            <div className="list-editor-rows">
              <div className="le-row">
                <div className="le-row-fields">
                  <div className="le-cell">
                    <Input
                      type="number"
                      value={scalarEntry == null ? "" : String(scalarEntry.points_per_currency ?? "")}
                      disabled={scalarInherited}
                      placeholder="Points per 1 unit local currency"
                      onChange={scalarInherited ? undefined : onScalarChange}
                    />
                  </div>
                </div>
                <div className="le-row-actions">
                  {scalarInherited && (
                    <React.Fragment>
                      <span className="le-tag"><LIcon name="Link" size={12}/> inherited</span>
                      <Btn variant="secondary" size="sm" onClick={onScalarOverride}>Override</Btn>
                    </React.Fragment>
                  )}
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* scalar — customer inactivity threshold in days (single int; mirrors the 1-column list layout) */}
        <section className="list-editor">
          <div className="list-editor-head">
            <div className="list-editor-title">Customer inactivity threshold (days)</div>
          </div>
          <div className="list-editor-table">
            <div className="le-head">
              <div className="le-row-fields">
                <div className="le-col-label">Days with no order before a customer is marked inactive</div>
              </div>
              <div className="le-head-spacer" aria-hidden="true"/>
            </div>
            <div className="list-editor-rows">
              <div className="le-row">
                <div className="le-row-fields">
                  <div className="le-cell">
                    <Input
                      type="number"
                      value={inactiveEntry == null ? "" : String(inactiveEntry.days ?? "")}
                      disabled={inactiveInherited}
                      placeholder="Days of inactivity"
                      onChange={inactiveInherited ? undefined : onInactiveChange}
                    />
                  </div>
                </div>
                <div className="le-row-actions">
                  {inactiveInherited && (
                    <React.Fragment>
                      <span className="le-tag"><LIcon name="Link" size={12}/> inherited</span>
                      <Btn variant="secondary" size="sm" onClick={onInactiveOverride}>Override</Btn>
                    </React.Fragment>
                  )}
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* scalar — HQ timezone (one global value; GA sets the default tz frame, HQ = Singapore) */}
        {scope === "ALL" && hqTzEntry && (
          <section className="list-editor">
            <div className="list-editor-head">
              <div className="list-editor-title">HQ timezone</div>
            </div>
            <div className="list-editor-table">
              <div className="le-head">
                <div className="le-row-fields">
                  <div className="le-col-label">Default timezone for GA / global views and multi-country records</div>
                </div>
                <div className="le-head-spacer" aria-hidden="true"/>
              </div>
              <div className="list-editor-rows">
                <div className="le-row">
                  <div className="le-row-fields">
                    <div className="le-cell">
                      <Select value={hqTzEntry.tz} onChange={onHqTzChange} options={tzOptions}/>
                    </div>
                  </div>
                  <div className="le-row-actions" aria-hidden="true"/>
                </div>
              </div>
            </div>
          </section>
        )}
      </div>
    );
  }

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