// Admin panel — edit pricing live
// Persisted via Tweaks-style EDITMODE block in app.jsx

const PRICING_GROUPS = [
  {
    id: 'vendors',
    title: 'Vendors',
    desc: 'Per-vendor profiles + custom prefilled links.',
    keys: [],
  },
  {
    id: 'core',
    title: 'Core rates',
    desc: 'The two linear-foot rates that drive most of the order.',
    keys: ['linear_ft_rate', 'toe_kick_rate'],
  },
  {
    id: 'panels',
    title: 'Finished side panels',
    desc: 'Per-cabinet flat fees — the exception to the linear-foot model.',
    keys: ['side_panel_one', 'side_panel_both'],
  },
  {
    id: 'surcharges',
    title: 'Surcharges',
    desc: 'Percent uplifts applied to the subtotal.',
    keys: ['rush_surcharge_pct', 'island_surcharge_pct'],
  },
  {
    id: 'materials',
    title: 'Box material multipliers',
    desc: 'Each cabinet\u2019s line is multiplied by this based on its box material.',
    keys: [
      'mat_birch', 'mat_maple', 'mat_maple_ply', 'mat_cherry', 'mat_oak',
      'mat_walnut', 'mat_melamine_white', 'mat_melamine_wood', 'mat_mdf',
      'mat_particle', 'mat_other',
    ],
  },
  {
    id: 'fees',
    title: 'Fees & tax',
    desc: 'Flat fees and tax applied at the end.',
    keys: ['trip_charge', 'minimum_job', 'tax_rate_pct'],
  },
];

function AdminScreen({ pricing, setPricing, vendors, setVendors, onClose, onReset }) {
  const [activeGroup, setActiveGroup] = React.useState('vendors');
  const [savedPulse, setSavedPulse] = React.useState(false);

  const update = (key, price) => {
    setPricing({ ...pricing, [key]: { ...pricing[key], price } });
    setSavedPulse(true);
    clearTimeout(window.__adminSavedTimer);
    window.__adminSavedTimer = setTimeout(() => setSavedPulse(false), 1200);
  };

  const group = PRICING_GROUPS.find(g => g.id === activeGroup);

  return (
    <div className="admin-overlay">
      <div className="admin-shell">
        <div className="admin-head">
          <div>
            <span className="eyebrow">Admin · Pricing</span>
            <h1 style={{ marginTop: 4 }}>Set the rates</h1>
            <p style={{ margin: '6px 0 0', color: 'var(--ink-soft)', fontSize: 14, maxWidth: 580 }}>
              Edit the rates below. Vendors see live totals as they fill out the cabinet form.
              Most work bills by the linear foot — finished side panels are the exception.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <span className={'admin-saved' + (savedPulse ? ' on' : '')}>
              <Icon.Check/> Saved
            </span>
            <button className="btn ghost" onClick={onReset} title="Reset all prices to defaults">
              Reset to defaults
            </button>
            <button className="btn primary" onClick={onClose}>
              <Icon.X/> Close admin
            </button>
          </div>
        </div>

        <div className="admin-body">
          <nav className="admin-nav">
            {PRICING_GROUPS.map(g => (
              <button key={g.id}
                className={'admin-nav-item' + (activeGroup === g.id ? ' active' : '')}
                onClick={() => setActiveGroup(g.id)}>
                <div className="t">{g.title}</div>
                <div className="s">{g.keys.length} item{g.keys.length === 1 ? '' : 's'}</div>
              </button>
            ))}
          </nav>

          <section className="admin-content">
            <div className="admin-group-head">
              <h2>{group.title}</h2>
              <p>{group.desc}</p>
            </div>

            {activeGroup === 'vendors' ? (
              <VendorsAdmin vendors={vendors} setVendors={setVendors}/>
            ) : (
              <div className="admin-rows">
              {group.keys.map(k => {
                const p = pricing[k] || DEFAULT_PRICING[k];
                if (!p) return null;
                const isPercent = p.unit && p.unit.startsWith('%');
                const isMultiplier = p.unit === 'multiplier';
                const prefix = isPercent || isMultiplier ? '' : '$';
                const suffix = isPercent ? '%' : isMultiplier ? '×' : '';
                return (
                  <div className="admin-row" key={k}>
                    <div className="row-info">
                      <div className="row-label">{p.label}</div>
                      <div className="row-meta">{p.unit}</div>
                      {p.note && <div className="row-note">{p.note}</div>}
                    </div>
                    <div className="row-input">
                      {prefix && <span className="affix">{prefix}</span>}
                      <input className="input mono"
                        type="number"
                        step={isMultiplier ? 0.01 : isPercent ? 0.5 : 1}
                        value={p.price}
                        onChange={e => update(k, parseFloat(e.target.value) || 0)}/>
                      {suffix && <span className="affix">{suffix}</span>}
                    </div>
                  </div>
                );
              })}
            </div>
            )}

            {activeGroup === 'core' && (
              <div className="admin-formula">
                <div className="eyebrow" style={{ marginBottom: 8 }}>How a cabinet line is calculated</div>
                <code>
                  cab_lf = (width_ft) + (doors × 0.5) + (drawers × 0.4) + (shelves × 0.25)<br/>
                  cab_total = cab_lf × ${pricing.linear_ft_rate?.price} × material_multiplier {'(+ island/peninsula uplift)'}
                </code>
              </div>
            )}
          </section>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AdminScreen, PRICING_GROUPS });
