const { useState: useStateC, useEffect: useEffectC } = React;

// ── Config key definitions ────────────────────────────────────────────────────

const FEATURE_FLAG_KEYS = [
  {
    key: 'feature.music_system',
    label: 'Music — search & attach',
    hint: 'Allow users to search, select, and attach music tracks to posts.',
  },
  {
    key: 'feature.music_playback',
    label: 'Music — feed playback',
    hint: 'Play attached music tracks in the feed. Disable while performance issues are being resolved.',
  },
];

const COMMISSION_KEYS = [
  { key: 'commission.store_product_rate',      label: 'Online product commission',        format: 'percent', hint: 'Charged on subtotal for all online orders' },
  { key: 'commission.instore_rate',             label: 'In-store (POS) commission',        format: 'percent', hint: 'Charged on POS sales through the sell tab' },
  { key: 'commission.standard.driver_rate',    label: 'Standard delivery — driver share', format: 'percent', hint: 'Driver receives this % of the delivery fee' },
  { key: 'commission.standard.platform_rate',  label: 'Standard delivery — platform share', format: 'percent', hint: 'Platform keeps this % of the delivery fee' },
  { key: 'commission.flash.driver_rate',       label: 'Flash delivery — driver share',    format: 'percent', hint: 'Driver receives this % of the flash fee' },
  { key: 'commission.flash.platform_rate',     label: 'Flash delivery — platform share',  format: 'percent', hint: 'Platform keeps this % of the flash fee' },
  { key: 'commission.tax_rate',                label: 'VAT rate',                         format: 'percent', hint: 'Applied to all sales (Nepal: 13%)' },
];

const DELIVERY_FEE_KEYS = [
  { key: 'delivery.standard.base_fee',              label: 'Standard base fee (NPR)',            format: 'number', hint: 'Same-day batched delivery' },
  { key: 'delivery.standard.per_km_fee',            label: 'Standard per-km fee (NPR)',          format: 'number' },
  { key: 'delivery.standard.free_distance_km',      label: 'Standard free distance (km)',        format: 'number' },
  { key: 'delivery.standard.free_shipping_threshold', label: 'Free shipping threshold — same day (NPR)', format: 'number', hint: 'Orders at or above this get free standard delivery' },
  { key: 'delivery.economy.base_fee',               label: 'Economy base fee (NPR)',             format: 'number', hint: 'Next-day batched delivery' },
  { key: 'delivery.economy.per_km_fee',             label: 'Economy per-km fee (NPR)',           format: 'number' },
  { key: 'delivery.economy.free_distance_km',       label: 'Economy free distance (km)',         format: 'number' },
  { key: 'delivery.economy.free_shipping_threshold', label: 'Free shipping threshold — next day (NPR)', format: 'number', hint: 'Orders at or above this get free economy delivery' },
  { key: 'delivery.flash.base_fee',                 label: 'Flash base fee (NPR)',               format: 'number', hint: 'On-demand 30-min delivery, always charged' },
  { key: 'delivery.flash.per_km_fee',               label: 'Flash per-km fee (NPR)',             format: 'number' },
  { key: 'delivery.flash.free_distance_km',         label: 'Flash free distance (km)',           format: 'number' },
  { key: 'delivery.flash.max_distance_km',          label: 'Flash max distance (km)',            format: 'number', hint: 'Buyers beyond this cannot select Flash delivery' },
  { key: 'delivery.operating_open_hour',            label: 'Delivery window — opens (24h)',      format: 'number', hint: 'Hour Flash becomes available platform-wide (e.g. 9 = 9 AM)' },
  { key: 'delivery.operating_close_hour',           label: 'Delivery window — closes (24h)',     format: 'number', hint: 'Hour Flash stops platform-wide (e.g. 21 = 9 PM)' },
];

const SUBSIDY_KEYS = [
  { key: 'delivery.free_shipping_driver_guarantee',          label: 'Driver guarantee (NPR)',          format: 'number', hint: 'Minimum paid to driver on free-shipping orders. Funded from product commission.' },
  { key: 'delivery.free_shipping_driver_commission_share',   label: 'Max commission share to driver',  format: 'percent', hint: 'Cap: driver cannot receive more than this % of the product commission on a free-delivery order.' },
];

// ── Helpers ───────────────────────────────────────────────────────────────────

function toDisplay(value, format) {
  return format === 'percent' ? (parseFloat(value) * 100).toFixed(0) : value;
}

function toStorage(display, format) {
  return format === 'percent' ? String(parseFloat(display) / 100) : display;
}

// ── Sub-components ────────────────────────────────────────────────────────────

const SectionC = ({ title, icon, children }) => {
  const I = window.Icons;
  return (
    <div className="panel" style={{ overflow: 'hidden' }}>
      <div className="panel-h">
        <span style={{ color: 'var(--ink-3)', display: 'flex' }}>{icon}</span>
        <span>{title}</span>
      </div>
      <div>{children}</div>
    </div>
  );
};

const RowDivider = () => <div style={{ height: 1, background: 'var(--hairline)', margin: '0' }} />;

const Toggle = ({ enabled, onChange, disabled }) => {
  const w = 40, h = 22, knob = 16;
  return (
    <button
      onClick={() => !disabled && onChange(!enabled)}
      disabled={disabled}
      style={{
        width: w, height: h, borderRadius: h, border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
        background: enabled ? 'var(--accent)' : 'var(--surface-3)',
        position: 'relative', transition: 'background 0.15s', flexShrink: 0,
        opacity: disabled ? 0.4 : 1,
      }}
    >
      <span style={{
        position: 'absolute', top: (h - knob) / 2, borderRadius: '50%',
        width: knob, height: knob, background: '#fff',
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
        left: enabled ? w - knob - (h - knob) / 2 : (h - knob) / 2,
        transition: 'left 0.15s',
      }} />
    </button>
  );
};

const FeatureFlagRow = ({ def, row, saving, statusVal, onToggle, loading }) => {
  const I = window.Icons;
  const enabled = row ? row.value === 'true' : false;
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '12px 16px' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{def.label}</div>
          {def.hint && <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{def.hint}</div>}
          {!row && !loading && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 3, fontSize: 11, color: 'var(--warn-ink, #b45309)' }}>
              <I.warn size={11} /> Not in database
            </div>
          )}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
          {saving ? (
            <I.refresh size={14} style={{ color: 'var(--ink-3)', animation: 'spin 1s linear infinite' }} />
          ) : (
            <Toggle enabled={enabled} onChange={onToggle} disabled={!row || loading} />
          )}
          <span style={{ fontSize: 12, fontWeight: 500, color: enabled ? 'var(--pos)' : 'var(--ink-3)', minWidth: 22 }}>
            {enabled ? 'On' : 'Off'}
          </span>
          {statusVal === 'ok' && <I.check size={13} style={{ color: 'var(--pos)' }} />}
          {statusVal === 'err' && <I.warn size={13} style={{ color: 'var(--neg)' }} />}
        </div>
      </div>
      <RowDivider />
    </>
  );
};

const ConfigNumRow = ({ def, row, editVal, saving, statusVal, onChange, onSave, loading }) => {
  const I = window.Icons;
  const exists = !!row;
  const isDirty = editVal !== undefined;
  const isPercent = def.format === 'percent';
  const displayVal = editVal !== undefined ? editVal : (row ? toDisplay(row.value, def.format) : '');

  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '11px 16px' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{def.label}</div>
          {def.hint && <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{def.hint}</div>}
          {!exists && !loading && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 3, fontSize: 11, color: 'var(--warn-ink, #b45309)' }}>
              <I.warn size={11} /> Not in database
            </div>
          )}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 3 }}>
            <input
              type="number"
              min="0"
              value={displayVal}
              onChange={e => exists && onChange(def.key, e.target.value)}
              disabled={!exists || loading}
              style={{
                width: 72, textAlign: 'right', fontSize: 13, fontFamily: 'var(--font-mono)',
                padding: '5px 8px', borderRadius: 5,
                border: isDirty ? '1px solid var(--accent)' : '1px solid var(--hairline)',
                background: exists ? 'var(--surface-2)' : 'var(--surface-3)',
                color: 'var(--ink)', outline: 'none',
                opacity: !exists ? 0.4 : 1, cursor: !exists ? 'not-allowed' : 'text',
              }}
            />
            {isPercent && <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>%</span>}
          </div>
          {isDirty && (
            <button
              className="btn primary"
              style={{ height: 28, fontSize: 11, gap: 4 }}
              onClick={() => onSave(def.key, def.format)}
              disabled={saving}
            >
              {saving ? <I.refresh size={11} /> : <I.check size={11} />}
              Save
            </button>
          )}
          {!isDirty && statusVal === 'ok' && <I.check size={13} style={{ color: 'var(--pos)' }} />}
          {statusVal === 'err' && <I.warn size={13} style={{ color: 'var(--neg)' }} />}
        </div>
      </div>
      <RowDivider />
    </>
  );
};

// ── ConfigPage ────────────────────────────────────────────────────────────────

const ConfigPage = () => {
  const I = window.Icons;
  const sb = window.supabaseClient;

  const [configs, setConfigs]   = useStateC({});
  const [edits, setEdits]       = useStateC({});
  const [saving, setSaving]     = useStateC({});
  const [statuses, setStatuses] = useStateC({});
  const [loading, setLoading]   = useStateC(true);
  const [dbStatus, setDbStatus] = useStateC('testing');

  // admin action log
  useEffectC(() => {
    if (!sb) return;

    // load platform_config
    sb.from('platform_config').select('*').then(({ data }) => {
      const map = {};
      for (const row of data || []) map[row.key] = row;
      setConfigs(map);
      setLoading(false);
    });

    // test db connection
    sb.from('user_profiles').select('id', { count: 'exact', head: true }).limit(1)
      .then(({ error }) => setDbStatus(error ? 'error' : 'connected'));

  }, []);

  const setStatus = (key, val) => {
    setStatuses(s => ({ ...s, [key]: val }));
    setTimeout(() => setStatuses(s => { const n = { ...s }; delete n[key]; return n; }), 2500);
  };

  const saveFlag = async (key, value) => {
    setSaving(s => ({ ...s, [key]: true }));
    const { error } = await sb.from('platform_config')
      .update({ value: String(value), updated_at: new Date().toISOString() })
      .eq('key', key);
    setSaving(s => ({ ...s, [key]: false }));
    if (error) { setStatus(key, 'err'); return; }
    setConfigs(c => ({ ...c, [key]: { ...c[key], value: String(value) } }));
    setStatus(key, 'ok');
  };

  const saveConfig = async (key, format) => {
    const raw = edits[key];
    if (raw === undefined) return;
    const stored = toStorage(raw, format);
    if (isNaN(parseFloat(stored))) return;
    setSaving(s => ({ ...s, [key]: true }));
    const { error } = await sb.from('platform_config')
      .update({ value: stored, updated_at: new Date().toISOString() })
      .eq('key', key);
    setSaving(s => ({ ...s, [key]: false }));
    if (error) { setStatus(key, 'err'); return; }
    setConfigs(c => ({ ...c, [key]: { ...c[key], value: stored } }));
    setEdits(e => { const n = { ...e }; delete n[key]; return n; });
    setStatus(key, 'ok');
  };

  const refresh = () => {
    setLoading(true);
    setDbStatus('testing');
    sb.from('platform_config').select('*').then(({ data }) => {
      const map = {};
      for (const row of data || []) map[row.key] = row;
      setConfigs(map);
      setLoading(false);
    });
    sb.from('user_profiles').select('id', { count: 'exact', head: true }).limit(1)
      .then(({ error }) => setDbStatus(error ? 'error' : 'connected'));
  };

  return (
    <div className="page" data-screen-label="Config">
      <div className="page-h">
        <div>
          <div className="ts">Platform fee structure, feature flags &amp; diagnostics</div>
          <h1>Config</h1>
        </div>
        <div className="acts">
          <button className="btn" onClick={refresh}>
            <I.refresh size={12} /> Refresh
          </button>
        </div>
      </div>

      {/* DB status bar */}
      <div className="panel" style={{ padding: '12px 16px', marginBottom: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
        <I.zap size={13} style={{ color: 'var(--ink-3)' }} />
        <span style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--ink-2)' }}>Database</span>
        {dbStatus === 'testing' && (
          <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--ink-3)' }}>
            <I.refresh size={12} /> Testing…
          </span>
        )}
        {dbStatus === 'connected' && (
          <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600, color: 'var(--pos)' }}>
            <I.check size={12} /> Connected
          </span>
        )}
        {dbStatus === 'error' && (
          <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600, color: 'var(--neg)' }}>
            <I.x size={12} /> Connection failed
          </span>
        )}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 20 }}>
          <div style={{ fontSize: 11.5, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)' }}>
            <span style={{ color: 'var(--ink-4)' }}>URL </span>
            {sb?._supabaseUrl?.substring(0, 28)}…
          </div>
          <div style={{ fontSize: 11.5, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)' }}>
            <span style={{ color: 'var(--ink-4)' }}>key </span>loaded
          </div>
        </div>
      </div>

      {/* Feature flags */}
      <SectionC title="Feature flags" icon={<I.zap size={13} />}>
        {FEATURE_FLAG_KEYS.map(def => (
          <FeatureFlagRow
            key={def.key}
            def={def}
            row={configs[def.key]}
            saving={!!saving[def.key]}
            statusVal={statuses[def.key]}
            onToggle={val => saveFlag(def.key, val)}
            loading={loading}
          />
        ))}
      </SectionC>

      {/* Commission rates */}
      <div style={{ marginTop: 14 }}>
        <SectionC title="Commission rates" icon={<I.coin size={13} />}>
          {COMMISSION_KEYS.map(def => (
            <ConfigNumRow
              key={def.key}
              def={def}
              row={configs[def.key]}
              editVal={edits[def.key]}
              saving={!!saving[def.key]}
              statusVal={statuses[def.key]}
              onChange={(k, v) => setEdits(e => ({ ...e, [k]: v }))}
              onSave={saveConfig}
              loading={loading}
            />
          ))}
        </SectionC>
      </div>

      {/* Delivery fees */}
      <div style={{ marginTop: 14 }}>
        <SectionC title="Delivery fees" icon={<I.truck size={13} />}>
          {DELIVERY_FEE_KEYS.map(def => (
            <ConfigNumRow
              key={def.key}
              def={def}
              row={configs[def.key]}
              editVal={edits[def.key]}
              saving={!!saving[def.key]}
              statusVal={statuses[def.key]}
              onChange={(k, v) => setEdits(e => ({ ...e, [k]: v }))}
              onSave={saveConfig}
              loading={loading}
            />
          ))}
        </SectionC>
      </div>

      {/* Free delivery driver subsidy */}
      <div style={{ marginTop: 14 }}>
        <SectionC title="Free delivery driver subsidy" icon={<I.star size={13} />}>
          {SUBSIDY_KEYS.map(def => (
            <ConfigNumRow
              key={def.key}
              def={def}
              row={configs[def.key]}
              editVal={edits[def.key]}
              saving={!!saving[def.key]}
              statusVal={statuses[def.key]}
              onChange={(k, v) => setEdits(e => ({ ...e, [k]: v }))}
              onSave={saveConfig}
              loading={loading}
            />
          ))}
        </SectionC>
      </div>

    </div>
  );
};

window.ConfigPage = ConfigPage;
