// admin/pages/commerce-ops.jsx — coupons, redirects, analytics, WA campaigns

function CouponsPage() {
  const [, bump] = React.useState(0);
  const refresh = () => bump((n) => n + 1);
  const list = (window.AmbadyCommerce && AmbadyCommerce.listPromotions && AmbadyCommerce.listPromotions()) || [];
  const [form, setForm] = React.useState({
    code: '', kind: 'percentage', value: 10, minCart: 0, maxDiscount: '', usageLimit: '', status: 'active'
  });
  const [err, setErr] = React.useState('');

  const save = () => {
    setErr('');
    if (!form.code.trim()) { setErr('Code required'); return; }
    const partial = {
      id: 'PROMO-' + Date.now().toString(36).toUpperCase(),
      tenantId: (window.AmbadyCommerce && AmbadyCommerce.get && AmbadyCommerce.get() && AmbadyCommerce.get().tenantId)
        || (window.ErpCore && ErpCore.AMBADY_TENANT && ErpCore.AMBADY_TENANT.id)
        || 'tenant_ambady_pebbles_garden',
      code: form.code,
      kind: form.kind,
      value: Number(form.value) || 0,
      minCart: Number(form.minCart) || 0,
      maxDiscount: form.maxDiscount === '' ? null : Number(form.maxDiscount),
      productIds: [],
      categoryIds: [],
      customerKeys: [],
      usageLimit: form.usageLimit === '' ? null : Number(form.usageLimit),
      perCustomerLimit: null,
      startsAt: null,
      endsAt: null,
      status: form.status,
    };
    const saved = AmbadyCommerce.createPromotion(partial);
    if (!saved) { setErr('Could not save promotion'); return; }
    setForm({ code: '', kind: 'percentage', value: 10, minCart: 0, maxDiscount: '', usageLimit: '', status: 'active' });
    refresh();
  };

  return (
    <div>
      <div className="mode-banner">Coupons · promotions engine (stacking disabled). Capability: live via AmbadyCommerce CRUD.</div>
      <div className="cc-grid-2">
        <div className="card card-pad">
          <div className="section-title">Create coupon</div>
          {err && <div className="banner-err">{err}</div>}
          <div className="form-grid">
            <div className="field"><label>Code</label><input className="inp" value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value })} placeholder="SPRING10" /></div>
            <div className="field"><label>Kind</label>
              <select className="sel" value={form.kind} onChange={(e) => setForm({ ...form, kind: e.target.value })}>
                <option value="percentage">Percentage</option>
                <option value="fixed">Fixed ₹</option>
                <option value="free_shipping">Free shipping</option>
              </select>
            </div>
            <div className="field"><label>Value</label><input className="inp" type="number" value={form.value} onChange={(e) => setForm({ ...form, value: e.target.value })} /></div>
            <div className="field"><label>Min cart ₹</label><input className="inp" type="number" value={form.minCart} onChange={(e) => setForm({ ...form, minCart: e.target.value })} /></div>
            <div className="field"><label>Max discount ₹</label><input className="inp" type="number" value={form.maxDiscount} onChange={(e) => setForm({ ...form, maxDiscount: e.target.value })} placeholder="optional" /></div>
            <div className="field"><label>Usage limit</label><input className="inp" type="number" value={form.usageLimit} onChange={(e) => setForm({ ...form, usageLimit: e.target.value })} placeholder="optional" /></div>
          </div>
          <button className="btn btn-primary" style={{ marginTop: 12 }} onClick={save}>Save coupon</button>
          <p className="muted" style={{ fontSize: '.78rem', marginTop: 10 }}>Stacking remains disabled in commerce core.</p>
        </div>
        <div className="card">
          <div className="panel-head"><h2>Active & stored</h2></div>
          <table className="tbl">
            <thead><tr><th>Code</th><th>Kind</th><th>Value</th><th>Used</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {list.map((p) => (
                <tr key={p.id}>
                  <td><b>{p.code}</b></td>
                  <td>{p.kind}</td>
                  <td>{p.kind === 'percentage' ? p.value + '%' : p.kind === 'fixed' ? money(p.value) : 'Free ship'}</td>
                  <td>{p.usageCount}{p.usageLimit != null ? ' / ' + p.usageLimit : ''}</td>
                  <td><span className="badge b-new">{p.status}</span></td>
                  <td>
                    {p.status === 'active' && (
                      <button className="btn btn-sm btn-ghost" onClick={() => { AmbadyCommerce.disablePromotion(p.id); refresh(); }}>Disable</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {!list.length && <Empty icon="tag" title="No coupons yet" note="Create a code — storefront applyCoupon revalidates on every quote." />}
        </div>
      </div>
    </div>
  );
}

function RedirectsPage() {
  const [, bump] = React.useState(0);
  const refresh = () => bump((n) => n + 1);
  const rows = (window.CommerceRedirects && CommerceRedirects.list()) || [];
  const [from, setFrom] = React.useState('#/products/old-slug');
  const [to, setTo] = React.useState('#/products/new-slug');
  const [err, setErr] = React.useState('');

  const add = () => {
    setErr('');
    const r = CommerceRedirects.upsert(from, to, { reason: 'manual' });
    if (!r.ok) { setErr(r.message); return; }
    setFrom(''); setTo('');
    refresh();
  };

  return (
    <div>
      <div className="mode-banner">Slug redirects · <code>apg.commerce.redirects.v1</code>. Auto-inserted when a product slug changes.</div>
      <div className="card card-pad" style={{ marginBottom: 16 }}>
        <div className="form-grid">
          <div className="field span2"><label>From hash</label><input className="inp" value={from} onChange={(e) => setFrom(e.target.value)} /></div>
          <div className="field span2"><label>To hash</label><input className="inp" value={to} onChange={(e) => setTo(e.target.value)} /></div>
        </div>
        {err && <div className="banner-err">{err}</div>}
        <button className="btn btn-primary" style={{ marginTop: 10 }} onClick={add}>Add redirect</button>
      </div>
      <div className="card">
        <table className="tbl">
          <thead><tr><th>From</th><th>To</th><th>Reason</th><th></th></tr></thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.id}>
                <td style={{ fontSize: '.82rem' }}>{r.from}</td>
                <td style={{ fontSize: '.82rem' }}>{r.to}</td>
                <td className="muted">{r.reason}</td>
                <td><button className="btn btn-sm btn-ghost" onClick={() => { CommerceRedirects.remove(r.id); refresh(); }}>Remove</button></td>
              </tr>
            ))}
          </tbody>
        </table>
        {!rows.length && <Empty icon="layers" title="No redirects" note="Rename a product slug to auto-create one, or add manually." />}
      </div>
    </div>
  );
}

function AnalyticsPage() {
  const metrics = window.OwnerMetrics ? OwnerMetrics.computeMetrics('30d') : null;
  let funnel = { view_product: 0, add_to_cart: 0, begin_checkout: 0, purchase: 0 };
  try {
    const rows = JSON.parse(localStorage.getItem('hap.analytics.v1') || '[]');
    rows.forEach((r) => {
      if (funnel[r.name] != null) funnel[r.name] += 1;
    });
  } catch (_) {}

  return (
    <div>
      <div className="mode-banner">Analytics · real funnel event counts from <code>hap.analytics.v1</code> + order KPIs. No fabricated conversion rates.</div>
      <div className="kpi-grid" style={{ marginBottom: 22 }}>
        <div className="kpi"><div className="kpi__label">Product views</div><div className="kpi__value">{funnel.view_product}</div></div>
        <div className="kpi"><div className="kpi__label">Add to cart</div><div className="kpi__value">{funnel.add_to_cart}</div></div>
        <div className="kpi"><div className="kpi__label">Begin checkout</div><div className="kpi__value">{funnel.begin_checkout}</div></div>
        <div className="kpi"><div className="kpi__label">Purchase events</div><div className="kpi__value">{funnel.purchase}</div></div>
      </div>
      {metrics && (
        <div className="kpi-grid" style={{ marginBottom: 22 }}>
          <div className="kpi"><div className="kpi__label">Orders (30d)</div><div className="kpi__value">{typeof metrics.orders === 'number' ? metrics.orders : ((metrics.orders && metrics.orders.count) || 0)}</div></div>
          <div className="kpi"><div className="kpi__label">Revenue (30d)</div><div className="kpi__value">{money(metrics.revenue || 0)}</div></div>
          <div className="kpi"><div className="kpi__label">AOV</div><div className="kpi__value">{money(metrics.aov || 0)}</div></div>
          <div className="kpi"><div className="kpi__label">Source</div><div className="kpi__value" style={{ fontSize: '.85rem' }}>{metrics.source || 'APG'}</div></div>
        </div>
      )}
      <p className="muted" style={{ fontSize: '.84rem' }}>
        Conversion % is not shown — event volumes alone do not prove a rate without a defined session denominator.
      </p>
    </div>
  );
}

function CampaignsPage() {
  const [, bump] = React.useState(0);
  const refresh = () => bump((n) => n + 1);
  const rows = (window.OwnerCampaigns && OwnerCampaigns.list()) || [];
  const settings = APG.getSettings();
  const templates = (settings.whatsapp && settings.whatsapp.templates) || {};
  const [form, setForm] = React.useState({
    name: '',
    audience: 'with_phone',
    templateKey: 'promo',
    message: templates.promo || '',
    scheduledAt: new Date(Date.now() + 3600000).toISOString().slice(0, 16),
  });

  const create = () => {
    OwnerCampaigns.create({
      name: form.name || 'WA campaign',
      audience: form.audience,
      templateKey: form.templateKey,
      message: form.message || templates[form.templateKey],
      scheduledAt: new Date(form.scheduledAt).toISOString(),
    });
    refresh();
  };

  const drainNow = () => {
    const d = OwnerCampaigns.drainDue(Date.now() + 1);
    if (window.OwnerRuntime) OwnerRuntime.bootstrapTick();
    refresh();
    alert('Drained ' + d.length + ' campaign(s). Deep-link tasks only — not Meta Ads.');
  };

  return (
    <div>
      <div className="mode-banner">
        Campaign scheduler · WhatsApp deep-link jobs only. Not an external ad-network launcher. Cap: marketing → live for scheduled WA.
      </div>
      <div className="cc-grid-2">
        <div className="card card-pad">
          <div className="section-title">Schedule WhatsApp campaign</div>
          <div className="form-grid">
            <div className="field span2"><label>Name</label><input className="inp" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
            <div className="field"><label>Audience</label>
              <select className="sel" value={form.audience} onChange={(e) => setForm({ ...form, audience: e.target.value })}>
                <option value="with_phone">Customers with phone</option>
                <option value="repeat">Repeat buyers</option>
                <option value="all_customers">All with phone</option>
              </select>
            </div>
            <div className="field"><label>Template key</label>
              <select className="sel" value={form.templateKey} onChange={(e) => {
                const k = e.target.value;
                setForm({ ...form, templateKey: k, message: templates[k] || form.message });
              }}>
                {Object.keys(templates).map((k) => <option key={k} value={k}>{k}</option>)}
              </select>
            </div>
            <div className="field span2"><label>Message</label><textarea className="ta" value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} /></div>
            <div className="field span2"><label>Schedule (local)</label><input className="inp" type="datetime-local" value={form.scheduledAt} onChange={(e) => setForm({ ...form, scheduledAt: e.target.value })} /></div>
          </div>
          <div className="row" style={{ gap: 8, marginTop: 12 }}>
            <button className="btn btn-primary" onClick={create}>Schedule</button>
            <button className="btn btn-soft" onClick={drainNow}>Drain due now</button>
          </div>
        </div>
        <div className="card">
          <div className="panel-head"><h2>Campaigns</h2></div>
          <table className="tbl">
            <thead><tr><th>Name</th><th>When</th><th>Audience</th><th>Status</th></tr></thead>
            <tbody>
              {rows.map((c) => (
                <tr key={c.id}>
                  <td><b>{c.name}</b><br /><span className="muted" style={{ fontSize: '.72rem' }}>{c.id}</span></td>
                  <td style={{ fontSize: '.82rem' }}>{c.scheduledAt}</td>
                  <td>{c.audience}</td>
                  <td>
                    <span className="badge b-new">{c.status}</span>
                    {c.results && <div className="muted" style={{ fontSize: '.72rem' }}>targeted {c.results.targeted}</div>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {!rows.length && <Empty icon="chat" title="No campaigns" note="Schedule a WhatsApp outreach — drained on owner runtime tick." />}
        </div>
      </div>
    </div>
  );
}

window.CouponsPage = CouponsPage;
window.RedirectsPage = RedirectsPage;
window.AnalyticsPage = AnalyticsPage;
window.CampaignsPage = CampaignsPage;
