/* Adeyy app — L1 Links home + L2 Create link. Live API version. */

function LinksHome({ app }) {
  const D = window.AdeyyData;
  const { links, campaigns } = app.state;
  const [q, setQ] = React.useState('');
  const [status, setStatus] = React.useState('all');
  const [camp, setCamp] = React.useState('all');

  /* Refresh links on mount */
  React.useEffect(() => {
    if (app.refreshLinks) app.refreshLinks();
  }, []);

  const activeCount = links.filter((l) => l.status === 'active').length;
  const shown = links.filter((l) => {
    if (status !== 'all' && l.status !== status) return false;
    if (camp !== 'all' && l.campaignId !== camp) return false;
    if (q) {
      const hay = (l.slug + ' ' + l.label + ' ' + l.dest).toLowerCase();
      if (hay.indexOf(q.toLowerCase()) === -1) return false;
    }
    return true;
  });

  return (
    <div data-screen-label="L1 Links home">
      <div className="apage-head">
        <h1>Links</h1>
        <span className="meta"><b>{activeCount}</b> active · <b>${activeCount}.00</b> / month</span>
        <span className="spacer"></span>
        <button className="abtn abtn-primary" onClick={() => app.go('create')}><Icon name="plus" size={15} />New link</button>
      </div>

      {app.loading ? <SkeletonTable rows={6} /> : links.length === 0 ? (
        <EmptyState
          title="Your first code is waiting."
          body="Paste a long link, get a short one and its QR code. Creating is free."
          cta="New link" onCta={() => app.go('create')} />
      ) : (
        <React.Fragment>
          <div className="filterbar">
            <div className="search">
              <Icon name="search" size={15} />
              <input className="ainput" placeholder="Search links and destinations" value={q} onChange={(e) => setQ(e.target.value)} />
            </div>
            {['all', 'active', 'inactive'].map((s) => (
              <button key={s} className={'achip' + (status === s ? ' active' : '')} onClick={() => setStatus(s)}>
                {s === 'all' ? 'All' : s === 'active' ? 'Active' : 'Inactive'}
              </button>
            ))}
            <select className="ainput" style={{ width: 'auto' }} value={camp} onChange={(e) => setCamp(e.target.value)}>
              <option value="all">All campaigns</option>
              {campaigns.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>

          {shown.length === 0 ? (
            <EmptyState title="Nothing matches." body="Try a different search, or clear the filters." />
          ) : (
            <table className="atable">
              <thead>
                <tr>
                  <th>Short link</th><th>Label</th><th>Destination</th>
                  <th className="r">Scans</th><th className="r">Clicks</th><th>Status</th><th>Created</th>
                </tr>
              </thead>
              <tbody>
                {shown.map((l) => (
                  <tr key={l.id} onClick={() => app.go('detail', { linkId: l.id })}>
                    <td className="tslug">adeyy.com/{l.slug}</td>
                    <td>{l.label || <span className="mutetext">·</span>}</td>
                    <td className="tdest" title={l.dest}>{l.dest.replace(/^https?:\/\//, '')}</td>
                    <td className="tnum">{D.num(l.scans)}</td>
                    <td className="tnum">{D.num(l.clicks)}</td>
                    <td><StatusPill on={l.status === 'active'} /></td>
                    <td className="tdate">{D.fmtDate(l.created)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </React.Fragment>
      )}
    </div>
  );
}

function CreateLink({ app }) {
  const D = window.AdeyyData;
  const API = window.AdeyyAPI;
  const { links, campaigns, retired } = app.state;
  const [dest, setDest] = React.useState('');
  const [destErr, setDestErr] = React.useState(null);
  const [mode, setMode] = React.useState('auto');
  const [custom, setCustom] = React.useState('');
  const [customStatus, setCustomStatus] = React.useState(null); /* null | 'checking' | 'ok' | string(error) */
  const [label, setLabel] = React.useState('');
  const [camp, setCamp] = React.useState('');
  const [newCamp, setNewCamp] = React.useState('');
  const [expiry, setExpiry] = React.useState('');
  const [active, setActive] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const autoRef = React.useRef(D.autoSlug(links.map((l) => l.slug)));

  const existing = links.map((l) => l.slug);

  /* Client-side slug check (fast) */
  const localSlugIssue = mode === 'custom' ? D.slugProblem(custom, existing, retired || []) : null;

  /* Debounced server-side slug check */
  React.useEffect(() => {
    if (mode !== 'custom' || !custom || localSlugIssue) {
      setCustomStatus(localSlugIssue || null);
      return;
    }
    setCustomStatus('checking');
    const timer = setTimeout(async () => {
      try {
        const result = await API.checkSlug(custom);
        setCustomStatus(result.available ? 'ok' : (result.reason || 'Not available'));
      } catch (e) {
        setCustomStatus('Could not check availability');
      }
    }, 400);
    return () => clearTimeout(timer);
  }, [custom, mode]);

  const slug = mode === 'custom' ? custom : autoRef.current;
  const previewSlug = (mode === 'custom' && custom && customStatus === 'ok') ? custom : autoRef.current;
  const slugOk = mode === 'auto' || (custom && customStatus === 'ok');

  function tryActivate(next) {
    if (next && !app.state.billing.card) {
      app.setCardPrompt(() => setActive(true));
      return;
    }
    setActive(next);
  }

  async function submit() {
    const dErr = D.validDest(dest.trim());
    if (dErr) { setDestErr(dErr); return; }
    if (!slugOk) return;
    setSaving(true);
    try {
      let campaignId = camp === '__new'
        ? await app.addCampaign(newCamp.trim())
        : (camp || null);

      const result = await API.createLink({
        destinationUrl: dest.trim(),
        slug: mode === 'custom' ? custom : undefined,
        label: label.trim() || undefined,
        campaignId: campaignId || undefined,
        expiresAt: expiry || undefined,
        activate: active
      });

      const newLink = API.adaptLink(result.link);
      app.update((s) => { s.links = [newLink].concat(s.links); });
      app.toast(active ? 'Link created and switched on' : 'Link created. Switch it on when you are ready');
      app.go('detail', { linkId: result.link.id });
    } catch (e) {
      if (e.message && e.message.includes('card on file')) {
        app.setCardPrompt(() => {
          setActive(true);
          submit();
        });
      } else {
        app.toast('Error: ' + e.message);
      }
    } finally {
      setSaving(false);
    }
  }

  return (
    <div data-screen-label="L2 Create link">
      <div className="apage-head">
        <button className="backlink" onClick={() => app.go('links')}><Icon name="back" size={14} />Links</button>
        <h1>New link</h1>
      </div>

      <div className="detail-grid">
        <div className="dcard">
          <div className="db" style={{ paddingTop: 18, display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div className="afield">
              <label>Destination</label>
              <input className={'ainput' + (destErr ? ' err' : '')} placeholder="https://the-long-link-you-want-people-to-reach.com/page"
                value={dest} onChange={(e) => { setDest(e.target.value); setDestErr(null); }} />
              {destErr ? <span className="hint" style={{ color: 'var(--danger)' }}>{destErr}</span>
                : <span className="hint">Where the link points right now. You can change this whenever you like.</span>}
            </div>

            <div className="afield">
              <label>Ending</label>
              <Seg value={mode} options={[{ value: 'auto', label: 'Automatic' }, { value: 'custom', label: 'Custom ending' }]} onChange={setMode} />
              {mode === 'auto' ? (
                <span className="hint">You will get <span className="slug" style={{ color: 'var(--ink)' }}>adeyy.com/{autoRef.current}</span></span>
              ) : (
                <React.Fragment>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className="slug" style={{ fontSize: 13, color: 'var(--ink-60)' }}>adeyy.com/</span>
                    <input className={'ainput mono' + (custom && customStatus && customStatus !== 'ok' && customStatus !== 'checking' ? ' err' : '')} style={{ maxWidth: 220 }}
                      placeholder="winter-menu" value={custom}
                      onChange={(e) => setCustom(e.target.value.toLowerCase())} />
                    {customStatus === 'checking' ? <span className="mutetext" style={{ fontSize: 12 }}>Checking…</span> : null}
                  </div>
                  <span className="hint" style={{ color: custom && customStatus === 'ok' ? 'var(--adeyy-ink)' : (custom && customStatus && customStatus !== 'checking' ? 'var(--danger)' : undefined) }}>
                    {!custom ? 'Lowercase letters, numbers and hyphens. Locks for life at first export or scan.' :
                      customStatus === 'checking' ? 'Checking availability…' :
                      customStatus === 'ok' ? 'Available. You can fix a typo until the code is first exported or scanned. After that it locks for life.' :
                      customStatus || ''}
                  </span>
                </React.Fragment>
              )}
            </div>

            <div className="formgrid">
              <div className="afield">
                <label>Label <span className="hint" style={{ display: 'inline', fontWeight: 400 }}>(optional)</span></label>
                <input className="ainput" placeholder="Window sticker · bookings" value={label} onChange={(e) => setLabel(e.target.value)} />
              </div>
              <div className="afield">
                <label>Campaign <span className="hint" style={{ display: 'inline', fontWeight: 400 }}>(optional)</span></label>
                <select className="ainput" value={camp} onChange={(e) => setCamp(e.target.value)}>
                  <option value="">None</option>
                  {campaigns.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                  <option value="__new">New campaign…</option>
                </select>
                {camp === '__new' ? (
                  <input className="ainput" placeholder="Campaign name" value={newCamp} onChange={(e) => setNewCamp(e.target.value)} />
                ) : null}
              </div>
            </div>

            <div className="afield" style={{ maxWidth: 240 }}>
              <label>Expiry <span className="hint" style={{ display: 'inline', fontWeight: 400 }}>(optional)</span></label>
              <input className="ainput" type="date" value={expiry} onChange={(e) => setExpiry(e.target.value)} />
              <span className="hint">On this date the code switches itself off and billing stops.</span>
            </div>

            <hr className="divider" style={{ margin: 0 }} />

            <div className="row-between">
              <div>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Switch on now</div>
                <div className="mutetext" style={{ fontSize: 12.5 }}>
                  {active ? '$1.00 per month, prorated from today.' : 'Off. The code will show the fallback page until you switch it on.'}
                </div>
              </div>
              <Toggle on={active} onChange={tryActivate} />
            </div>

            <div style={{ display: 'flex', gap: 10 }}>
              <button className="abtn abtn-primary abtn-lg" onClick={submit} disabled={saving}>
                {saving ? 'Creating…' : 'Create link'}
              </button>
              <button className="abtn abtn-quiet" onClick={() => app.go('links')}>Cancel</button>
            </div>
          </div>
        </div>

        <div className="dcard" style={{ position: 'sticky', top: 20 }}>
          <div className="dh"><h2>Its QR code</h2><span className="meta">One per link</span></div>
          <div className="db" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ border: '1px solid var(--border-1)', borderRadius: 4, overflow: 'hidden' }}>
              <QrSvg slug={previewSlug} config={app.state.defaultQr} />
            </div>
            <span className="slug" style={{ fontSize: 13, fontWeight: 700, textAlign: 'center' }}>adeyy.com/{previewSlug}</span>
            <span className="mutetext" style={{ fontSize: 12, textAlign: 'center' }}>
              Generated with your default design. Restyle and export it from the link page after creating.
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LinksHome, CreateLink });
