// Public Pastebin-style screens.
//   PasteCreate  — anonymous paste form, POST /api/paste, redirects to view
//   PasteView    — reads /api/paste/:id, displays content + actions
// Both are mounted from index.html as full-page screens (no auth required).
// Visually they reuse the same accent / typography / chip / btn classes as
// the rest of the marketing site so they feel like one product.

const PASTE_MAX_BYTES = 100 * 1024;       // mirror backend cap
const PASTE_MAX_TITLE = 120;

function PasteCreate({ onNav }) {
  const [title, setTitle] = React.useState('');
  const [body, setBody]   = React.useState('');
  const [busy, setBusy]   = React.useState(false);
  const [err, setErr]     = React.useState(null);

  const bodyBytes = React.useMemo(
    () => new Blob([body]).size,
    [body],
  );
  const overLimit = bodyBytes > PASTE_MAX_BYTES;

  const submit = async () => {
    if (!body.trim() || overLimit) return;
    setBusy(true);
    setErr(null);
    try {
      const r = await window.api('/api/paste', {
        method: 'POST',
        body: { title: title.trim(), body },
      });
      // Update browser URL so the page is shareable, then nav to view screen.
      window.__pasteId = r.id;
      try { history.pushState(null, '', r.url); } catch {}
      onNav('paste-view');
    } catch (e) {
      setErr(window.apiErrorMessage(e));
    } finally {
      setBusy(false);
    }
  };

  const onKey = (e) => {
    // Ctrl/Cmd-Enter submits, mirroring the convention from most paste sites.
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); submit(); }
  };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg-0)', display: 'flex', flexDirection: 'column' }}>
      <PasteHeader onNav={onNav}/>
      <AdBanners position="top"/>

      <main style={{ flex: 1, padding: '32px 20px', maxWidth: 940, width: '100%', margin: '0 auto' }}>
        <div style={{ marginBottom: 22 }}>
          <h1 style={{ fontSize: 26, fontWeight: 600, margin: 0, letterSpacing: '-0.01em' }}>New paste</h1>
          <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: '6px 0 0' }}>
            Paste anything you want to share. Links live for 30 days. No login required.
          </p>
        </div>

        <div style={{ background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 12, padding: 18 }}>
          {/* Title */}
          <input
            type="text"
            placeholder="Title (optional)"
            value={title}
            onChange={e => setTitle(e.target.value.slice(0, PASTE_MAX_TITLE))}
            disabled={busy}
            style={{
              width: '100%', padding: '10px 12px', fontSize: 14,
              background: 'var(--bg-0)', color: 'var(--fg-0)',
              border: '1px solid var(--line)', borderRadius: 8,
              marginBottom: 12, outline: 'none',
            }}
          />

          {/* Body */}
          <textarea
            placeholder="Paste your text here…"
            value={body}
            onChange={e => setBody(e.target.value)}
            onKeyDown={onKey}
            disabled={busy}
            spellCheck={false}
            style={{
              width: '100%', minHeight: 360, padding: '12px 14px',
              fontFamily: 'JetBrains Mono, ui-monospace, monospace', fontSize: 13, lineHeight: 1.55,
              background: 'var(--bg-0)', color: 'var(--fg-0)',
              border: `1px solid ${overLimit ? 'var(--err)' : 'var(--line)'}`, borderRadius: 8,
              resize: 'vertical', outline: 'none',
            }}
          />

          {/* Status row */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12, fontSize: 11, color: 'var(--fg-3)', gap: 12, flexWrap: 'wrap' }}>
            <div>
              {overLimit
                ? <span style={{ color: 'var(--err)' }}>Too large — {fmtBytes(bodyBytes)} / {fmtBytes(PASTE_MAX_BYTES)} limit</span>
                : <span>{fmtBytes(bodyBytes)} / {fmtBytes(PASTE_MAX_BYTES)}</span>}
              <span style={{ marginLeft: 12 }}>· expires in 30 days</span>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ color: 'var(--fg-3)' }}>⌘ + Enter to submit</span>
              <button
                className="btn btn-primary"
                onClick={submit}
                disabled={busy || !body.trim() || overLimit}
                style={{ padding: '8px 18px' }}
              >
                {busy ? 'Creating…' : 'Create paste'}
              </button>
            </div>
          </div>

          {err && (
            <div role="alert" style={{
              marginTop: 12, padding: '10px 14px', borderRadius: 6,
              fontSize: 12, color: 'var(--err)',
              background: 'color-mix(in oklab, var(--err) 8%, transparent)',
              border: '1px solid color-mix(in oklab, var(--err) 25%, transparent)',
            }}>{err}</div>
          )}
        </div>

        <AdBanners position="bottom"/>
      </main>

      <PasteFooter/>
    </div>
  );
}

function PasteView({ onNav, pasteId }) {
  const [data, setData]   = React.useState(null);
  const [err, setErr]     = React.useState(null);
  const [copied, setCopied] = React.useState(false);

  React.useEffect(() => {
    if (!pasteId) { setErr('No paste ID specified.'); return; }
    setData(null);
    setErr(null);
    window.api(`/api/paste/${encodeURIComponent(pasteId)}`)
      .then(setData)
      .catch(e => {
        if (e && e.status === 404) setErr('This paste does not exist or has expired.');
        else setErr(window.apiErrorMessage(e));
      });
  }, [pasteId]);

  const copy = async () => {
    if (!data) return;
    try {
      await navigator.clipboard.writeText(data.body);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch { /* ignore */ }
  };

  // Trigger a client-side download of the paste body. Filename is derived
  // from the title (sanitized) or the slug if no title was given. Saved as
  // .txt because we don't track language/syntax — plain text is honest.
  const download = () => {
    if (!data) return;
    const safeTitle = (data.title || '')
      .toLowerCase()
      .replace(/[^a-z0-9_-]+/g, '_')
      .replace(/^_+|_+$/g, '')
      .slice(0, 60);
    const filename = `${safeTitle || data.id}.txt`;
    const blob = new Blob([data.body], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    // Free the blob URL on the next tick — synchronous revoke can race
    // with the browser's actual download trigger in some browsers.
    setTimeout(() => URL.revokeObjectURL(url), 100);
  };

  const fmtDate = (iso) => {
    if (!iso) return '—';
    const d = new Date(iso + (iso.endsWith('Z') ? '' : 'Z'));
    return d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
  };
  const fmtRelative = (iso) => {
    if (!iso) return '';
    const ms = new Date(iso + (iso.endsWith('Z') ? '' : 'Z')).getTime() - Date.now();
    const days = Math.round(ms / 86400000);
    if (days <= 0) return 'soon';
    return days === 1 ? 'in 1 day' : `in ${days} days`;
  };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg-0)', display: 'flex', flexDirection: 'column' }}>
      <PasteHeader onNav={onNav}/>
      <AdBanners position="top"/>

      <main style={{ flex: 1, padding: '32px 20px', maxWidth: 940, width: '100%', margin: '0 auto' }}>
        {err && (
          <div role="alert" style={{
            padding: '20px 24px', borderRadius: 12,
            fontSize: 14, color: 'var(--err)',
            background: 'color-mix(in oklab, var(--err) 8%, transparent)',
            border: '1px solid color-mix(in oklab, var(--err) 25%, transparent)',
          }}>
            {err}
            <div style={{ marginTop: 12 }}>
              <button className="btn btn-primary" onClick={() => onNav('paste')}>Create a new paste</button>
            </div>
          </div>
        )}

        {!err && !data && (
          <div style={{ padding: 64, textAlign: 'center', color: 'var(--fg-3)' }}>
            Loading…
          </div>
        )}

        {data && (
          <>
            {/* Header strip: title + meta + actions */}
            <div style={{ marginBottom: 16 }}>
              <h1 style={{
                fontSize: 22, fontWeight: 600, margin: 0, letterSpacing: '-0.01em',
                wordBreak: 'break-word',
              }}>
                {data.title || <span style={{ color: 'var(--fg-3)', fontWeight: 400 }}>untitled paste</span>}
              </h1>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 8, fontSize: 11, color: 'var(--fg-3)' }}>
                <span className="mono">#{data.id}</span>
                <span>· created {fmtDate(data.created_at)}</span>
                <span>· expires {fmtRelative(data.expires_at)}</span>
                <span>· {fmtBytes(data.size_bytes)}</span>
                <span>· {data.view_count.toLocaleString()} view{data.view_count === 1 ? '' : 's'}</span>
              </div>
            </div>

            {/* Action bar */}
            <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-ghost" onClick={copy} style={{ fontSize: 12, padding: '6px 12px' }}>
                {copied ? '✓ Copied' : 'Copy text'}
              </button>
              <button className="btn btn-ghost" onClick={download} style={{ fontSize: 12, padding: '6px 12px' }}>
                Download
              </button>
              <a
                href={`/api/paste/${encodeURIComponent(data.id)}/raw`}
                target="_blank" rel="noopener"
                className="btn btn-ghost"
                style={{ fontSize: 12, padding: '6px 12px', textDecoration: 'none' }}
              >Raw</a>
              <button
                className="btn btn-ghost"
                onClick={() => onNav('paste')}
                style={{ fontSize: 12, padding: '6px 12px' }}
              >New paste</button>
            </div>

            {/* Body with line numbers. Plain text only — no syntax highlighting
                in v1; can be added later. */}
            <PasteBody body={data.body}/>

            <AdBanners position="bottom"/>
          </>
        )}
      </main>

      <PasteFooter/>
    </div>
  );
}

// Renders the paste body as a code-style block with line numbers down the
// left gutter. Wraps long lines so wide content stays readable.
function PasteBody({ body }) {
  const lines = React.useMemo(() => body.split('\n'), [body]);
  const gutterWidth = String(lines.length).length * 8 + 18;   // px

  return (
    <div style={{
      background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 10,
      overflow: 'hidden',
    }}>
      <div style={{
        display: 'flex',
        fontFamily: 'JetBrains Mono, ui-monospace, monospace',
        fontSize: 13, lineHeight: 1.55,
      }}>
        {/* Gutter — line numbers, non-selectable so triple-click "select all"
            on the body doesn't pull in the numbers. */}
        <div
          aria-hidden
          style={{
            width: gutterWidth, padding: '14px 8px 14px 14px',
            color: 'var(--fg-3)', textAlign: 'right',
            background: 'var(--bg-2)', borderRight: '1px solid var(--line)',
            userSelect: 'none', flexShrink: 0,
          }}
        >
          {lines.map((_, i) => <div key={i}>{i + 1}</div>)}
        </div>
        {/* Body — preserves whitespace but wraps long lines */}
        <pre style={{
          margin: 0, padding: '14px 16px',
          color: 'var(--fg-0)',
          whiteSpace: 'pre-wrap', wordBreak: 'break-word',
          flex: 1, overflowX: 'auto',
        }}>{body}</pre>
      </div>
    </div>
  );
}

// Side-by-side promo banners shaped like ad slots (à la Pastebin / leaked.tools).
// Two visually-distinct cards — one is the headline pitch, the other a
// secondary "your ad here"-style slot we own ourselves to keep readers
// looking at this format. Both link to the proxies landing page.
//
// Used both above the paste form/content (entry-of-page glance) and below
// (exit-of-page consideration). Same component twice rather than two
// near-identical ones to keep them in sync visually.
function AdBanners({ position }) {
  // Slight padding tweak so the top instance hugs the header line and the
  // bottom one breathes more before the footer.
  const padY = position === 'top' ? '14px 16px 12px' : '20px 16px 16px';
  return (
    <div style={{
      padding: padY,
      maxWidth: 1100, width: '100%', margin: '0 auto',
      // auto-fit + minmax = two columns on desktop, stacks below ~640px wide.
      // No media query needed.
      display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14,
    }}>
      <AdSlot
        kind="primary"
        eyebrow="🚀 Residential proxies"
        title="67proxies — plans from $6.70"
        sub="Worldwide pool · rotating IPs · HTTP/HTTPS · pay as you go"
        cta="View plans →"
      />
      <AdSlot
        kind="secondary"
        eyebrow="⚡ 100 Mbps · Daily"
        title="Unlimited bandwidth · $15"
        sub="Dedicated 100 Mbps residential · 24h unmetered · worldwide pool"
        cta="Get started →"
      />
    </div>
  );
}

// Single ad-slot card. Two visual variants share the structure: an outlined
// box with an animated accent border on hover, eyebrow + title + sub copy,
// and a CTA button on the right. Click anywhere navigates to landing — the
// whole card is the link, not just the button (matches typical ad UX).
function AdSlot({ kind, eyebrow, title, sub, cta }) {
  const [hovered, setHovered] = React.useState(false);
  const go = () => { window.__setScreen && window.__setScreen('landing'); };

  // Two variants: primary uses a saturated accent fill, secondary uses an
  // outlined "available slot" look so the pair has visual contrast like the
  // reference (filled banner + bordered banner side-by-side).
  const isPrimary = kind === 'primary';
  const baseBg = isPrimary
    ? 'linear-gradient(135deg, color-mix(in oklab, var(--accent) 22%, var(--bg-1)) 0%, color-mix(in oklab, var(--accent) 10%, var(--bg-1)) 100%)'
    : 'var(--bg-1)';
  const borderColor = hovered
    ? 'var(--accent)'
    : isPrimary
      ? 'color-mix(in oklab, var(--accent) 45%, var(--line))'
      : 'color-mix(in oklab, var(--accent) 30%, var(--line))';
  const glow = hovered
    ? `0 0 0 1px var(--accent), 0 0 24px -4px color-mix(in oklab, var(--accent) 60%, transparent)`
    : isPrimary
      ? `0 0 18px -6px color-mix(in oklab, var(--accent) 50%, transparent)`
      : 'none';

  return (
    <button
      onClick={go}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        textAlign: 'left', cursor: 'pointer',
        background: baseBg,
        border: `1px solid ${borderColor}`,
        borderRadius: 10,
        // Roomier padding + min-height. Reference has chunky 90 Tier-style
        // banner blocks (~110-130px tall); 110 here lands in the same range
        // while leaving the layout responsive.
        padding: '20px 22px',
        display: 'flex', alignItems: 'center', gap: 16,
        boxShadow: glow,
        transition: 'border-color 120ms ease, box-shadow 180ms ease, transform 120ms ease',
        transform: hovered ? 'translateY(-1px)' : 'none',
        minHeight: 110,
      }}
    >
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 11, color: isPrimary ? 'var(--accent)' : 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 500, marginBottom: 6 }}>
          {eyebrow}
        </div>
        <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--fg-0)', marginBottom: 4, letterSpacing: '-0.01em', lineHeight: 1.25 }}>
          {title}
        </div>
        {/* Allow the subtitle to wrap to two lines now that the banner has
            room — old single-line ellipsis hid useful copy. */}
        <div style={{ fontSize: 12, color: 'var(--fg-3)', lineHeight: 1.45 }}>
          {sub}
        </div>
      </div>
      <span style={{
        flexShrink: 0,
        background: isPrimary ? 'var(--accent)' : 'transparent',
        color: isPrimary ? 'var(--accent-ink)' : 'var(--accent)',
        border: isPrimary ? 'none' : '1px solid var(--accent)',
        borderRadius: 6,
        padding: '10px 16px', fontSize: 12, fontWeight: 600,
        whiteSpace: 'nowrap',
      }}>{cta}</span>
    </button>
  );
}

// Header bar — minimal, links to landing + the paste form.
function PasteHeader({ onNav }) {
  return (
    <header style={{
      borderBottom: '1px solid var(--line)',
      padding: '14px 20px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: 'var(--bg-1)',
    }}>
      <button
        onClick={() => onNav('landing')}
        style={{ background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10, padding: 0 }}
      >
        <Logo67 size={22}/>
        <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-0)' }}>67proxies</span>
        <span style={{ fontSize: 12, color: 'var(--fg-3)', marginLeft: 4 }}>· paste</span>
      </button>
      <div style={{ display: 'flex', gap: 8 }}>
        <button
          className="btn btn-ghost"
          onClick={() => onNav('paste')}
          style={{ fontSize: 12, padding: '6px 12px' }}
        >New paste</button>
        <button
          className="btn btn-primary"
          onClick={() => onNav('landing')}
          style={{ fontSize: 12, padding: '6px 12px' }}
        >Get proxies</button>
      </div>
    </header>
  );
}

function PasteFooter() {
  return (
    <footer style={{
      borderTop: '1px solid var(--line)',
      padding: '16px 20px', marginTop: 32,
      fontSize: 11, color: 'var(--fg-3)',
      display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
    }}>
      <span>© 67proxies · paste expires after 30 days</span>
      <span>
        <a href="/" style={{ color: 'inherit' }}>home</a>
        <span style={{ margin: '0 8px' }}>·</span>
        <a href="/paste" style={{ color: 'inherit' }}>new paste</a>
      </span>
    </footer>
  );
}

// Local helper. Pasted bodies range from a few characters to tens of KB so
// auto-pick the unit. Decimal (KB = 1000B) for byte counts users will
// compare against the explicit "100 KB" cap message.
function fmtBytes(n) {
  const x = Number(n) || 0;
  if (x < 1024)        return `${x} B`;
  if (x < 1024 * 1024) return `${(x / 1024).toFixed(1)} KB`;
  return `${(x / 1024 / 1024).toFixed(2)} MB`;
}

window.PasteCreate = PasteCreate;
window.PasteView   = PasteView;
