/* Adeyy app — L6 Campaigns + L7 Bulk create. Live API version. */

function Campaigns({ app }) {
  const D = window.AdeyyData;
  const API = window.AdeyyAPI;
  const { campaigns, links } = app.state;
  const [naming, setNaming] = React.useState(false);
  const [name, setName] = React.useState('');
  const [renaming, setRenaming] = React.useState(null);
  const [saving, setSaving] = React.useState(false);

  function rollup(cid) {
    const ls = links.filter((l) => l.campaignId === cid);
    return {
      n: ls.length,
      active: ls.filter((l) => l.status === 'active').length,
      scans: ls.reduce((a, l) => a + l.scans, 0),
      clicks: ls.reduce((a, l) => a + l.clicks, 0)
    };
  }

  async function handleSave() {
    if (!name.trim()) return;
    setSaving(true);
    try {
      if (renaming) {
        await API.renameCampaign(renaming, name.trim());
        app.update((s) => { const c = s.campaigns.find((x) => x.id === renaming); if (c) c.name = name.trim(); });
        app.toast('Campaign renamed');
      } else {
        await app.addCampaign(name.trim());
        app.toast('Campaign created');
      }
      setNaming(false); setRenaming(null);
    } catch (e) {
      app.toast('Error: ' + e.message);
    } finally {
      setSaving(false);
    }
  }

  return (
    <div data-screen-label="L6 Campaigns">
      <div className="apage-head">
        <h1>Campaigns</h1>
        <span className="meta"><b>{campaigns.length}</b> groups</span>
        <span className="spacer"></span>
        <button className="abtn abtn-primary" onClick={() => { setName(''); setNaming(true); }}><Icon name="plus" size={15} />New campaign</button>
      </div>

      {campaigns.length === 0 ? (
        <EmptyState title="No campaigns yet." body="A campaign is a named group of links, so a whole push reads as one number."
          cta="New campaign" onCta={() => { setName(''); setNaming(true); }} />
      ) : (
        <table className="atable">
          <thead>
            <tr><th>Campaign</th><th className="r">Links</th><th className="r">Active</th><th className="r">Scans</th><th className="r">Clicks</th><th></th></tr>
          </thead>
          <tbody>
            {campaigns.map((c) => {
              const r = rollup(c.id);
              return (
                <tr key={c.id} onClick={() => app.go('analytics', { campaignId: c.id })}>
                  <td style={{ fontWeight: 600 }}>{c.name}</td>
                  <td className="tnum">{r.n}</td>
                  <td className="tnum">{r.active}</td>
                  <td className="tnum">{D.num(r.scans)}</td>
                  <td className="tnum">{D.num(r.clicks)}</td>
                  <td style={{ textAlign: 'right' }} onClick={(e) => e.stopPropagation()}>
                    <button className="abtn abtn-ghost abtn-sm" onClick={() => { setRenaming(c.id); setName(c.name); }}>Rename</button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      )}

      {(naming || renaming) ? (
        <Modal title={renaming ? 'Rename campaign' : 'New campaign'} onClose={() => { setNaming(false); setRenaming(null); }}>
          <p>{renaming ? 'Renaming changes nothing else. Links stay where they are.' : 'Group links so a whole push reads as one number.'}</p>
          <input className="ainput" placeholder="winter-launch" value={name} autoFocus onChange={(e) => setName(e.target.value)} style={{ marginBottom: 16 }} />
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="abtn abtn-quiet" onClick={() => { setNaming(false); setRenaming(null); }}>Cancel</button>
            <button className="abtn abtn-primary" disabled={!name.trim() || saving} onClick={handleSave}>
              {saving ? (renaming ? 'Renaming…' : 'Creating…') : (renaming ? 'Rename' : 'Create')}
            </button>
          </div>
        </Modal>
      ) : null}
    </div>
  );
}

/* ---------- L7 Bulk create ---------- */

const BULK_SAMPLE = 'destination,ending,label\nhttps://my-cafe.com.au/menus/spring-2026,spring-menu,Spring menu\nhttps://my-cafe.com.au/loyalty,,Loyalty card insert\nhttps://www.instagram.com/mycafe.au,follow-us,Sticker sheet';

function BulkCreate({ app }) {
  const D = window.AdeyyData;
  const API = window.AdeyyAPI;
  const [raw, setRaw] = React.useState('');
  const [activateAll, setActivateAll] = React.useState(false);
  const [creating, setCreating] = React.useState(false);

  const rows = React.useMemo(() => {
    if (!raw.trim()) return [];
    const lines = raw.trim().split(/\n+/);
    const start = /^destination/i.test(lines[0]) ? 1 : 0;
    const existing = app.state.links.map((l) => l.slug);
    const seen = [];
    return lines.slice(start).map((line) => {
      const [dest = '', ending = '', label = ''] = line.split(',').map((x) => x.trim());
      let problem = D.validDest(dest);
      let slug = ending.toLowerCase();
      if (!problem && slug) {
        problem = D.slugProblem(slug, existing.concat(seen), app.state.retired || []);
      }
      if (!slug) slug = D.autoSlug(existing.concat(seen));
      if (!problem) seen.push(slug);
      return { dest, slug, label, problem, auto: !ending };
    });
  }, [raw, app.state.links]);

  const good = rows.filter((r) => !r.problem);

  async function createAll() {
    if (activateAll && !app.state.billing.card) { app.setCardPrompt(() => {}); return; }
    setCreating(true);
    try {
      const apiRows = good.map((r) => ({
        destinationUrl: r.dest,
        slug: r.auto ? undefined : r.slug,
        label: r.label || undefined
      }));
      const result = await API.bulkCreate(apiRows, activateAll);
      const created = (result.created || []).map(API.adaptLink);
      app.update((s) => {
        created.forEach((l) => s.links.unshift(l));
      });
      app.toast(created.length + ' links created' + (activateAll ? ' and switched on' : ''));
      app.go('links');
    } catch (e) {
      if (e.message && e.message.includes('card on file')) {
        app.setCardPrompt(() => createAll());
      } else {
        app.toast('Error: ' + e.message);
      }
    } finally {
      setCreating(false);
    }
  }

  return (
    <div data-screen-label="L7 Bulk create">
      <div className="apage-head">
        <button className="backlink" onClick={() => app.go('links')}><Icon name="back" size={14} />Links</button>
        <h1>Bulk create</h1>
        <span className="spacer"></span>
        <button className="abtn abtn-ghost abtn-sm" onClick={() => setRaw(BULK_SAMPLE)}>Use sample CSV</button>
      </div>

      <div className="detail-grid" style={{ gridTemplateColumns: '380px 1fr' }}>
        <div className="dcard">
          <div className="dh"><h2>Paste CSV</h2><span className="meta">destination, ending, label</span></div>
          <div className="db" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <textarea className="ainput mono" rows={9} style={{ resize: 'vertical', fontSize: 11.5, lineHeight: 1.6 }}
              placeholder={'destination,ending,label\nhttps://example.com.au/page,my-ending,Poster A'}
              value={raw} onChange={(e) => setRaw(e.target.value)}></textarea>
            <span className="mutetext" style={{ fontSize: 12 }}>
              Leave the ending blank for an automatic one. Endings follow the same rules as everywhere else: reserved and taken endings are flagged before anything is created.
            </span>
            <div className="row-between">
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>Switch them all on</div>
                <div className="mutetext" style={{ fontSize: 12 }}>{activateAll ? '$1.00 each per month, prorated.' : 'Created off. Activate later, one by one or here.'}</div>
              </div>
              <Toggle on={activateAll} onChange={(v) => {
                if (v && !app.state.billing.card) { app.setCardPrompt(() => setActivateAll(true)); return; }
                setActivateAll(v);
              }} />
            </div>
            <button className="abtn abtn-primary" disabled={good.length === 0 || creating} onClick={createAll}>
              {creating ? 'Creating…' : ('Create ' + (good.length > 0 ? good.length + ' ' : '') + (good.length === 1 ? 'link' : 'links'))}
            </button>
          </div>
        </div>

        <div className="dcard">
          <div className="dh"><h2>Preview</h2><span className="meta">{rows.length ? good.length + ' of ' + rows.length + ' ready' : 'Nothing pasted yet'}</span></div>
          <div className="db">
            {rows.length === 0 ? (
              <EmptyState title="Paste rows to preview them." body="Each row becomes a link and its QR code. Nothing is created until you say so." />
            ) : (
              <table className="atable">
                <thead><tr><th>Short link</th><th>Destination</th><th>Label</th><th>Check</th></tr></thead>
                <tbody>
                  {rows.map((r, i) => (
                    <tr key={i} style={{ cursor: 'default' }}>
                      <td className="tslug">adeyy.com/{r.slug}{r.auto ? <span className="mutetext" style={{ fontWeight: 400 }}> · auto</span> : null}</td>
                      <td className="tdest">{r.dest.replace(/^https?:\/\//, '')}</td>
                      <td>{r.label || <span className="mutetext">·</span>}</td>
                      <td style={{ fontSize: 12.5, color: r.problem ? 'var(--danger)' : 'var(--adeyy-ink)', fontWeight: 600 }}>
                        {r.problem || 'Ready'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Campaigns, BulkCreate });
