import { useEffect, useState } from 'react';

const FAKE_ADS = [
  {
    brand: 'ServerFuel™',
    tagline: 'Keep the forge warm',
    blurb: 'Fictional energy drink for fictional servers. 0 calories, 100% vibes.',
  },
  {
    brand: 'CloudCrate Hosting',
    tagline: 'Boxes in the sky',
    blurb: 'Not a real host. Just a polite reminder that bandwidth isn’t free.',
  },
  {
    brand: 'FairPlay Shield',
    tagline: 'One account, few tabs',
    blurb: 'Demo ad. Thanks for not multi-boxing the backend into orbit.',
  },
];

export default function SessionLimitOverlay({ max = 2 }) {
  const [ad] = useState(
    () => FAKE_ADS[Math.floor(Math.random() * FAKE_ADS.length)]
  );
  const [phase, setPhase] = useState('idle'); // idle | watching | done
  const [secondsLeft, setSecondsLeft] = useState(5);

  useEffect(() => {
    if (phase !== 'watching') return undefined;
    if (secondsLeft <= 0) {
      setPhase('done');
      return undefined;
    }
    const t = setTimeout(() => setSecondsLeft((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [phase, secondsLeft]);

  const startAd = () => {
    setSecondsLeft(5);
    setPhase('watching');
  };

  return (
    <div className="session-limit-overlay" role="alertdialog" aria-modal="true" aria-labelledby="session-limit-title">
      <div className="session-limit-box">
        <p className="session-limit-kicker">Connection limit</p>
        <h2 id="session-limit-title">Too many windows</h2>
        <p className="session-limit-lead">
          This account already has <strong>{max}</strong> tabs/windows connected.
          Close another one, then reload this page.
        </p>
        <p className="session-limit-respect">
          Merci de ne pas abuser ni exploiter de bugs pour multiplier les sessions —
          ça charge le serveur pour tout le monde. Un compte, un usage raisonnable.
        </p>

        <div className="session-limit-ad">
          <div className="session-limit-ad-label">Sponsored · fictif</div>
          <div className={`session-limit-ad-screen${phase === 'watching' ? ' playing' : ''}`}>
            {phase === 'idle' && (
              <>
                <div className="session-limit-ad-brand">{ad.brand}</div>
                <div className="session-limit-ad-tag">{ad.tagline}</div>
                <p className="muted">{ad.blurb}</p>
                <button type="button" className="btn" onClick={startAd}>
                  Watch ad (5s) · support the servers
                </button>
              </>
            )}
            {phase === 'watching' && (
              <>
                <div className="session-limit-ad-brand">{ad.brand}</div>
                <div className="session-limit-ad-progress" aria-hidden>
                  <div
                    className="session-limit-ad-progress-fill"
                    style={{ width: `${((5 - secondsLeft) / 5) * 100}%` }}
                  />
                </div>
                <p className="session-limit-ad-countdown">Ad playing… {secondsLeft}s</p>
                <p className="muted">Fictional spot — thanks for the support gesture.</p>
              </>
            )}
            {phase === 'done' && (
              <>
                <div className="session-limit-ad-brand">Thanks!</div>
                <p>
                  Pub fictive terminée. Pour débloquer cette page : ferme un autre onglet,
                  puis recharge.
                </p>
                <button
                  type="button"
                  className="btn secondary"
                  onClick={() => window.location.reload()}
                >
                  Reload page
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
