// tnych-landing.jsx — CHCreations public landing

/* Fallback shown only if the API is unreachable */
const FALLBACK_LINKS = [
{ code: 'hub', dest: 'chcreations.net', label: 'CHCreations Hub' },
{ code: 'vrcid', dest: 'vrcidlinker.com', label: 'VRC ID Linker' },
{ code: 'bd', dest: 'vrclinked.com', label: 'Burrow Defender' },
{ code: 'kofi', dest: 'ko-fi.com/chadhendrixs', label: 'Ko-fi' }];

/* Clicks are tracked server-side: rows link to /:code and the server
   records the hit before redirecting — nothing is logged in the browser. */
function displayDest(dest) {
  return String(dest || '').replace(/^https?:\/\//i, '').replace(/\/$/, '');
}

/* ── Inject styles once ── */
(function injectLandingStyles() {
  if (document.getElementById('landing-styles')) return;
  const el = document.createElement('style');
  el.id = 'landing-styles';
  el.textContent = `
    @keyframes skeletonPulse {
      0%, 100% { opacity: 0.28; }
      50%       { opacity: 0.5; }
    }
    .skel {
      background: rgba(100, 130, 200, 0.15);
      border-radius: 3px;
      animation: skeletonPulse 1.1s ease-in-out infinite;
    }

    /* columns: Name | Destination | /code */
    .tbl-row {
      display: grid;
      grid-template-columns: 1fr 1fr 90px;
      align-items: center;
      gap: 0 16px;
      padding: 0 20px;
      min-height: 50px;
      text-decoration: none;
      color: inherit;
      border-bottom: 1px solid rgba(100, 130, 220, 0.12);
      transition: background 0.13s;
      cursor: pointer;
    }
    .tbl-row:last-child { border-bottom: none; }
    .tbl-row:hover { background: rgba(100, 130, 220, 0.07); }

    .cell-label {
      font-size: 15px;
      font-weight: 600;
      color: rgba(230, 235, 248, 0.95);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .cell-dest {
      font-size: 13px;
      color: rgba(160, 175, 215, 0.65);
      font-family: monospace;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .cell-code {
      font-size: 13px;
      font-weight: 700;
      color: rgba(212, 148, 42, 0.85);
      font-family: monospace;
      letter-spacing: 0.02em;
      text-align: right;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .tbl-row:hover .cell-label { color: rgba(240, 243, 255, 1); }
    .tbl-row:hover .cell-dest  { color: rgba(180, 195, 235, 0.85); }
    .tbl-row:hover .cell-code  { color: #e0a535; }

    @media (max-width: 480px) {
      .tbl-row { grid-template-columns: 1fr 80px; }
      .cell-dest { display: none; }
    }
  `;
  document.head.appendChild(el);
})();

/* ── Skeleton ── */
function SkeletonRows() {
  return (
    <>
      {[100, 75, 90, 60].map((w, i) =>
      <div key={i} className="tbl-row" style={{ pointerEvents: 'none' }}>
          <div className="skel" style={{ width: `${w}%`, maxWidth: 130, height: 13, animationDelay: `${i * 90}ms` }} />
          <div className="skel" style={{ width: '65%', maxWidth: 110, height: 11, animationDelay: `${i * 90 + 50}ms` }} />
          <div className="skel" style={{ width: 44, height: 12, marginLeft: 'auto', animationDelay: `${i * 90 + 80}ms` }} />
        </div>
      )}
    </>);

}

/* ── Table row ── */
function PublicLinkRow({ link, visible, index }) {
  return (
    <a
      className="tbl-row"
      href={`/${link.code}`}
      target="_blank"
      rel="noopener"
      style={{
        opacity: visible ? 1 : 0,
        transform: visible ? 'none' : 'translateY(5px)',
        transitionDelay: visible ? `${index * 60}ms` : '0ms',
        transition: 'opacity 0.3s ease, transform 0.3s ease, background 0.13s'
      }}>
      
      <span className="cell-label">{link.label}</span>
      <span className="cell-dest">{displayDest(link.dest)}</span>
      <span className="cell-code">/{link.code}</span>
    </a>);

}

/* ── Links table ── */
function PublicLinksTable() {
  const [links, setLinks] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    let alive = true;
    // keep the skeleton up a moment so the load doesn't flash
    const minDelay = new Promise((r) => setTimeout(r, 550));
    const data = fetch('/api/public-links')
      .then((r) => r.json())
      .then((rows) => rows.map((r) => ({ code: r.shortCode, dest: r.dest, label: r.label || `/${r.shortCode}` })))
      .catch(() => FALLBACK_LINKS);
    Promise.all([data, minDelay]).then(([rows]) => {
      if (!alive) return;
      setLinks(rows);
      setLoading(false);
      setVisible(true);
    });
    return () => { alive = false; };
  }, []);

  return (
    <div style={{ borderTop: '1px solid rgba(100, 130, 220, 0.16)', marginTop: 28 }}>
      <div style={{ fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'rgba(160, 180, 225, 0.55)', textAlign: "center", fontSize: "16px", lineHeight: "1.4", textDecoration: 'underline', height: "5px", margin: "0px", padding: "10px 0px 0px" }}>Currently Active Public Links

      </div>
      <div style={{
        margin: '28px 32px 0',
        border: '1px solid rgba(100, 130, 220, 0.18)',
        borderRadius: 6,
        background: 'rgba(6, 10, 28, 0.55)',
        overflow: 'hidden',
        boxShadow: 'inset 0 1px 8px rgba(0,0,0,0.3)',
        marginBottom: 24
      }}>
        {loading ? <SkeletonRows /> :
        (links || []).map((link, i) =>
        <PublicLinkRow key={link.code} link={link} visible={visible} index={i} />
        )
        }
        {!loading && (!links || links.length === 0) &&
        <div className="tbl-row" style={{ pointerEvents: 'none', justifyContent: 'center' }}>
          <span className="cell-dest" style={{ gridColumn: '1 / -1', textAlign: 'center' }}>No public links yet.</span>
        </div>
        }
      </div>
    </div>);

}

function Landing({ domain, onLoginClick }) {
  return (
    <div style={{
      minHeight: '100dvh',
      fontFamily: "'Space Grotesk', system-ui, sans-serif",
      color: 'rgba(220, 228, 248, 0.95)',
      background: 'transparent',
      display: 'flex',
      flexDirection: 'column'
    }}>

      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 20px 56px' }}>
        <div style={{
          width: '100%',
          maxWidth: 620,
          background: 'rgba(10, 14, 36, 0.78)',
          border: '1px solid rgba(100, 130, 220, 0.22)',
          borderRadius: 20,
          overflow: 'hidden',
          backdropFilter: 'blur(16px)',
          WebkitBackdropFilter: 'blur(16px)'
        }}>

          {/* Card header */}
          <div style={{ padding: '56px 52px 0' }}>
            <div style={{ fontSize: 46, fontWeight: 700, letterSpacing: '-0.03em', color: '#f5dfa0', marginBottom: 10, textAlign: 'center' }}>
              {domain}
            </div>
            <div style={{ fontSize: 17, color: 'rgba(180, 200, 240, 0.88)', lineHeight: 1.7, marginBottom: 20, textAlign: "center" }}>
              Hello! This is a URL shortener for{' '}
              <a href="https://chcreations.net" target="_blank" rel="noopener"
              style={{ color: '#d4942a', textDecoration: 'none' }}>
                CHCreations
              </a>{' '}projects. Links I make for QR codes (or easy embeds) just forward to the project automatically.
            </div>
            <p style={{ fontSize: 16, color: 'rgba(160, 180, 225, 0.75)', lineHeight: 1.8, marginBottom: 0 }}>&emsp;&emsp;This site is a private system like tinyurl or bitly, the only difference is I can easily make and use links I want without having to worry about a 3rd party company deleting my URLs after a year. This site uses industry standard data analytics in an attempt to gain overall customer based interests and trends.<br/><br/>&emsp;&emsp;No data here is shared with any 3rd party (aside from what Google collects) and is automatically deleted in rolling 90 day windows.</p>
          </div>

          {/* Links table */}
          <PublicLinksTable />

          {/* Footer */}
          <div style={{ padding: '16px 52px', borderTop: '1px solid rgba(100, 130, 220, 0.12)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 12, color: 'rgba(120, 145, 195, 0.55)' }}>© 2026 CHCreations</span>
            <button
              onClick={onLoginClick}
              style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 12, color: 'rgba(120, 145, 195, 0.4)', fontFamily: 'inherit', padding: 0, transition: 'color 0.12s' }}
              onMouseEnter={(e) => e.currentTarget.style.color = 'rgba(180, 200, 240, 0.75)'}
              onMouseLeave={(e) => e.currentTarget.style.color = 'rgba(120, 145, 195, 0.4)'}>
              admin</button>
          </div>

        </div>
      </div>

      {/* GA4 notice */}
      <div style={{ background: 'rgba(5, 8, 22, 0.82)', borderTop: '1px solid rgba(100, 130, 220, 0.18)', padding: '10px 24px', fontSize: 12.5, color: 'rgba(160, 180, 225, 0.8)', textAlign: 'center', lineHeight: 1.6, backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)' }}>
        <strong style={{ color: '#d4972e', fontWeight: 600 }}>Analytics notice:</strong>{' '}
        This site uses Google Analytics (GA4) to count page visits and link clicks. No personally identifiable information is collected.{' '}
        <a href="https://policies.google.com/privacy" target="_blank" rel="noopener" style={{ color: '#d4972e', textDecoration: 'none' }}>Google's Privacy Policy</a>
      </div>

    </div>);

}

Object.assign(window, { Landing });