// =================================================================
// pw-screens-coupons.jsx — Publisher Admin §6 Coupon Offers · §8 Brand Codes
// =================================================================

// Plain-English discount summary for a code/template.
function discountSummary(c) {
  if (!c) return "—";
  const amt = c.discount_type === "percent" ? `${c.discount_value}% off` : `${fmt.currency(c.discount_value, c.currency)} off`;
  const bits = [amt];
  if (c.applies_to) bits.push(`on ${c.applies_to === "both" ? "products & services" : c.applies_to + "s"}`);
  if (c.min_order_amount) bits.push(`min ${fmt.currency(c.min_order_amount, c.currency)}`);
  if (c.max_discount_amount) bits.push(`cap ${fmt.currency(c.max_discount_amount, c.currency)}`);
  return bits.join(" · ");
}

// ---------- Offer form drawer (§6) ----------
const OfferDrawer = ({ open, onClose, offer, codes, onSave }) => {
  const blank = { code_id: codes[0]?.code_id || "", coin_cost: 250, max_per_user: 1, total_limit: 500, valid_from: "2026-06-01", valid_until: "2026-12-31", status: "active" };
  const [f, setF] = React.useState(blank);
  React.useEffect(() => { if (open) setF(offer ? { ...offer } : { ...blank }); }, [open, offer]);
  const set = (patch) => setF(prev => ({ ...prev, ...patch }));
  const code = codes.find(c => c.code_id === f.code_id);

  return (
    <Drawer open={open} onClose={onClose} title={offer ? "Edit coupon offer" : "New coupon offer"} width={520}
      footer={<><Btn kind="secondary" onClick={onClose}>Cancel</Btn>
        <Btn kind="primary" disabled={!f.code_id} onClick={() => { onSave(f); onClose(); }}>{offer ? "Save offer" : "Create offer"}</Btn></>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
        <FieldRow label="Discount code" hint="The assigned brand template this offer reveals." layout="stacked">
          <Select value={f.code_id} onChange={v => set({ code_id: v })}
            options={codes.map(c => ({ label: `${c.brand} · ${c.name}`, value: c.code_id }))}/>
          {code && (
            <div className="pw-code-summary">
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontFamily: "var(--mono)", fontSize: 12.5, color: "var(--ink)" }}>{code.code}</span>
                <StatusPill status={code.status}/>
              </div>
              <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 4 }}>{discountSummary(code)}</div>
            </div>
          )}
        </FieldRow>
        <FieldRow label="Coin cost" hint="Coins a reader spends to reveal the code.">
          <NumberStepper value={f.coin_cost} onChange={v => set({ coin_cost: v })} min={0} max={100000} step={50} suffix="coins"/>
        </FieldRow>
        <FieldRow label="Limits" layout="stacked">
          <FieldGroup cols={2}>
            <div><label className="pw-lbl">Per user</label><NumberStepper value={f.max_per_user} onChange={v => set({ max_per_user: v })} min={1} max={20}/></div>
            <div><label className="pw-lbl">Total limit</label><NumberStepper value={f.total_limit} onChange={v => set({ total_limit: v })} min={1} max={1000000} step={50}/></div>
          </FieldGroup>
        </FieldRow>
        <FieldRow label="Validity" layout="stacked">
          <FieldGroup cols={2}>
            <div><label className="pw-lbl">From</label><Input type="date" value={f.valid_from} onChange={e => set({ valid_from: e.target.value })}/></div>
            <div><label className="pw-lbl">Until</label><Input type="date" value={f.valid_until} onChange={e => set({ valid_until: e.target.value })}/></div>
          </FieldGroup>
        </FieldRow>
        <FieldRow label="Status">
          <SegmentedControl value={f.status} onChange={v => set({ status: v })} options={[{ label: "Active", value: "active" }, { label: "Paused", value: "paused" }, { label: "Ended", value: "ended" }]}/>
        </FieldRow>
        <InlineHelp icon={<IconInfo size={13}/>}>The code stays hidden from readers until they spend coins to reveal it.</InlineHelp>
      </div>
    </Drawer>
  );
};

// =================================================================
// §6 Coupon Offers
// =================================================================
const CouponOffersScreen = ({ data, setData }) => {
  const [drawer, setDrawer] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const codeOf = (id) => data.storeDiscountCodes.find(c => c.code_id === id) || {};

  // Prefill from "Create offer from this code" (§8 CTA).
  React.useEffect(() => {
    if (window.__pwPrefillCode) {
      setEditing(null);
      setDrawer(true);
      const pre = window.__pwPrefillCode;
      window.__pwPrefillCode = null;
      setTimeout(() => { window.__pwOfferPrefillCode = pre; }, 0);
    }
  }, []);

  const save = (f) => {
    if (editing) {
      window.__api.write("updateCouponOffer",
        d => ({ ...d, couponOffers: d.couponOffers.map(o => o.offer_id === editing.offer_id ? { ...o, ...f } : o) }),
        { params: { offer_id: editing.offer_id }, body: f, ok: "Offer updated", err: "Couldn’t update offer" });
    } else {
      const offer_id = "off_" + Math.random().toString(36).slice(2, 7);
      window.__api.write("createCouponOffer",
        d => ({ ...d, couponOffers: [{ ...f, offer_id, claimed_count: 0 }, ...d.couponOffers] }),
        { body: { ...f, offer_id }, ok: "Offer created", err: "Couldn’t create offer" });
    }
  };

  return (
    <Screen>
      <PageHead icon={IconGift} title="Coupon Offers" subtitle="Tap-to-reveal brand offers your readers unlock with coins."
        actions={<Btn kind="primary" icon={<IconPlus size={15}/>} onClick={() => { setEditing(null); setDrawer(true); }}>New offer</Btn>}/>

      <div className="pw-offer-grid">
        {data.couponOffers.map(o => {
          const c = codeOf(o.code_id);
          const pct = Math.round((o.claimed_count / o.total_limit) * 100);
          return (
            <Card key={o.offer_id}>
              <div className="pw-offer-head">
                <div style={{ minWidth: 0 }}>
                  <div className="pw-offer-brand">{c.brand}</div>
                  <div className="pw-offer-name">{c.name}</div>
                </div>
                <StatusPill status={o.status}/>
              </div>
              <div className="pw-offer-meta">
                <span className="pw-offer-cost"><IconCoin size={14} style={{ color: "var(--warn)" }}/> {fmt.number(o.coin_cost)}</span>
                <span style={{ fontSize: 12, color: "var(--muted)" }}>to reveal</span>
              </div>
              <div style={{ fontSize: 12.5, color: "var(--muted)", margin: "2px 0 14px" }}>{discountSummary(c)}</div>
              <ProgressBar value={o.claimed_count} max={o.total_limit} tone={pct >= 100 ? "warn" : "accent"}
                label="Claimed" format={(v) => fmt.number(v)}/>
              <div className="pw-offer-foot">
                <span style={{ fontSize: 11.5, color: "var(--muted)" }}>{fmt.date(o.valid_from)} – {fmt.date(o.valid_until)} · max {o.max_per_user}/user</span>
                <Btn kind="ghost" size="sm" icon={<IconPencil size={13}/>} onClick={() => { setEditing(o); setDrawer(true); }}>Edit</Btn>
              </div>
            </Card>
          );
        })}
      </div>

      <OfferDrawer open={drawer} onClose={() => setDrawer(false)} offer={editing} codes={data.storeDiscountCodes} onSave={save}/>

      <style>{`
        .pw-offer-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--gap); }
        .pw-offer-grid > * { min-width: 0; }
        @media (max-width: 1100px) { .pw-offer-grid { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 640px) { .pw-offer-grid { grid-template-columns: 1fr; } }
        .pw-offer-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 10px; }
        .pw-offer-brand { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
        .pw-offer-name { font-size: 15.5px; font-weight: 600; color: var(--ink); margin-top: 2px; }
        .pw-offer-meta { display: flex; align-items: baseline; gap: 6px; margin: 12px 0 2px; }
        .pw-offer-cost { display: inline-flex; align-items: center; gap: 5px; font-size: 20px; font-weight: 600; font-family: var(--mono); }
        .pw-offer-foot { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 14px; }
      `}</style>
    </Screen>
  );
};

// =================================================================
// §8 Brand Codes (assigned, read-only) — grouped by brand
// =================================================================
const BrandCodesScreen = ({ data }) => {
  const [q, setQ] = React.useState("");
  const codes = data.storeDiscountCodes.filter(c => (c.code + c.name + c.brand).toLowerCase().includes(q.toLowerCase()));
  const groups = codes.reduce((acc, c) => { (acc[c.brand] = acc[c.brand] || []).push(c); return acc; }, {});

  const createOffer = (code_id) => {
    window.__pwPrefillCode = code_id;
    window.__nav("coupon-offers");
  };

  return (
    <Screen>
      <PageHead icon={IconTag} title="Brand Codes" subtitle="Discount codes brands have assigned to you. Turn them into coupon offers." />
      <Toolbar search={q} onSearchChange={setQ} searchPlaceholder="Search codes or brands"/>

      {Object.keys(groups).length === 0 && (
        <Card><EmptyState icon={<IconTag size={30}/>} title="No codes" description="No brand codes match your search."/></Card>
      )}

      {Object.entries(groups).map(([brand, list]) => (
        <Card key={brand} title={brand} subtitle={`${list.length} code${list.length === 1 ? "" : "s"} assigned`} padded={false}>
          <DataTable rows={list} keyField="code_id" density="compact"
            columns={[
              { key: "code", label: "Code", render: r => <span style={{ fontFamily: "var(--mono)", fontSize: 12.5, color: "var(--ink)" }}>{r.code}</span> },
              { key: "name", label: "Name" },
              { key: "discount", label: "Discount", sortable: false, render: r => <span style={{ fontSize: 12.5, color: "var(--ink-2)" }}>{discountSummary(r)}</span> },
              { key: "valid_until", label: "Expires", align: "right", render: r => <span style={{ fontFamily: "var(--mono)", fontSize: 12 }}>{fmt.date(r.valid_until)}</span> },
              { key: "status", label: "Status", render: r => <StatusPill status={r.status}/> },
              { key: "_cta", label: "", sortable: false, align: "right", render: r => (
                <Btn kind="secondary" size="sm" icon={<IconGift size={13}/>} disabled={r.status !== "active"}
                  onClick={() => createOffer(r.code_id)}>Create offer</Btn>) },
            ]}/>
        </Card>
      ))}
    </Screen>
  );
};

Object.assign(window, { CouponOffersScreen, BrandCodesScreen, OfferDrawer, discountSummary });
