// Inlinr — Public preview page (no auth required)
// Route: /preview/{shareId}

const { useState, useEffect, useCallback, useRef } = React;

const PREVIEW_DEVICES = [
  { id: "desktop", label: "Desktop", width: 720, icon: "monitor" },
  { id: "tablet",  label: "Tablet",  width: 480, icon: "tablet" },
  { id: "mobile",  label: "Mobile",  width: 360, icon: "mobile" },
];

const hashPwd = async (pwd) => {
  const enc = new TextEncoder().encode(pwd);
  const buf = await crypto.subtle.digest("SHA-256", enc);
  return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, "0")).join("");
};

const PreviewPage = ({ shareId }) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [device, setDevice] = useState("desktop");
  const [darkMode, setDarkMode] = useState(false);
  const [locked, setLocked] = useState(false);
  const [pwdInput, setPwdInput] = useState("");
  const [pwdError, setPwdError] = useState(false);
  const [unlocking, setUnlocking] = useState(false);
  const iframeRef = useRef(null);
  const trackedRef = useRef(false);

  useEffect(() => {
    if (!shareId) { setError("No preview ID"); setLoading(false); return; }

    fbDb.collection("previews").doc(shareId).get()
      .then(snap => {
        if (!snap.exists) {
          setError("expired");
          setLoading(false);
          return;
        }
        const d = snap.data();

        if (d.expiresAt) {
          const exp = d.expiresAt.toDate ? d.expiresAt.toDate() : new Date(d.expiresAt);
          if (exp < new Date()) {
            setError("expired");
            setLoading(false);
            return;
          }
        }

        setData(d);
        setLocked(!!d.passwordHash);
        setLoading(false);

        if (d.trackOpens && !trackedRef.current) {
          trackedRef.current = true;
          fbDb.collection("previews").doc(shareId).update({
            openCount: firebase.firestore.FieldValue.increment(1),
          }).catch(() => {});
        }
      })
      .catch(err => {
        console.error("Preview load failed:", err);
        setError("load");
        setLoading(false);
      });
  }, [shareId]);

  const handleUnlock = useCallback(async () => {
    if (!pwdInput || !data?.passwordHash) return;
    setUnlocking(true);
    setPwdError(false);
    const hash = await hashPwd(pwdInput);
    if (hash === data.passwordHash) {
      setLocked(false);
    } else {
      setPwdError(true);
    }
    setUnlocking(false);
  }, [pwdInput, data]);

  const handleKeyDown = useCallback((e) => {
    if (e.key === "Enter") handleUnlock();
  }, [handleUnlock]);

  useEffect(() => {
    if (!iframeRef.current || !data?.html || locked) return;
    const doc = iframeRef.current.contentDocument;
    if (!doc) return;

    let html = data.html;
    if (darkMode) {
      html = html.replace(
        "</head>",
        `<style>
          body { background-color: #1a1a1e !important; }
          .email-row { background-color: #1a1a1e !important; }
          h1,h2,h3,h4,p,span,div,a { color: #e8e8ec !important; }
          hr { border-color: #3f3f46 !important; }
        </style></head>`
      );
    }

    doc.open();
    doc.write(html);
    doc.close();
  }, [data, darkMode, locked, device]);

  if (loading) {
    return (
      <div className="pv-page">
        <div className="pv-loading">
          <span className="pv-spinner" />
          <span>Loading preview…</span>
        </div>
      </div>
    );
  }

  if (error === "expired") {
    return (
      <div className="pv-page">
        <div className="pv-error">
          <div className="pv-error-icon">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="9"/>
              <path d="M12 7v5l3 2"/>
            </svg>
          </div>
          <h2>Preview expired</h2>
          <p>This preview link has expired or been revoked. Ask the sender for a new link.</p>
          <a className="pv-brand-link" href="/">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <rect x="4" y="6" width="14" height="2.4" rx="1.2" fill="currentColor"/>
              <rect x="4" y="11" width="9" height="2.4" rx="1.2" fill="currentColor" opacity="0.55"/>
              <rect x="4" y="16" width="12" height="2.4" rx="1.2" fill="currentColor" opacity="0.3"/>
            </svg>
            Powered by Inlinr
          </a>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="pv-page">
        <div className="pv-error">
          <h2>Unable to load preview</h2>
          <p>Something went wrong. Please try again or contact the sender.</p>
        </div>
      </div>
    );
  }

  if (locked) {
    return (
      <div className="pv-page">
        <div className="pv-lock-gate">
          <div className="pv-lock-card">
            <div className="pv-lock-icon">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="11" width="18" height="11" rx="2"/>
                <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
              </svg>
            </div>
            <h2>Password required</h2>
            <p>This preview is protected. Enter the password to continue.</p>
            <div className="pv-lock-title">{data.campaignTitle || "Email preview"}</div>
            <div className={`pv-lock-input${pwdError ? " is-error" : ""}`}>
              <input
                type="password"
                placeholder="Enter password"
                value={pwdInput}
                onChange={(e) => { setPwdInput(e.target.value); setPwdError(false); }}
                onKeyDown={handleKeyDown}
                autoFocus
              />
              <button onClick={handleUnlock} disabled={unlocking || !pwdInput}>
                {unlocking ? "…" : "Unlock"}
              </button>
            </div>
            {pwdError && <div className="pv-lock-error">Incorrect password. Try again.</div>}
            <a className="pv-brand-link" href="/">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                <rect x="4" y="6" width="14" height="2.4" rx="1.2" fill="currentColor"/>
                <rect x="4" y="11" width="9" height="2.4" rx="1.2" fill="currentColor" opacity="0.55"/>
                <rect x="4" y="16" width="12" height="2.4" rx="1.2" fill="currentColor" opacity="0.3"/>
              </svg>
              Powered by Inlinr
            </a>
          </div>
        </div>
      </div>
    );
  }

  const currentDevice = PREVIEW_DEVICES.find(d => d.id === device);
  const expiresAt = data.expiresAt
    ? (data.expiresAt.toDate ? data.expiresAt.toDate() : new Date(data.expiresAt))
    : null;

  return (
    <div className="pv-page">
      <header className="pv-header">
        <div className="pv-header-left">
          <a href="/" className="pv-logo">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <rect x="4" y="6" width="14" height="2.4" rx="1.2" fill="currentColor"/>
              <rect x="4" y="11" width="9" height="2.4" rx="1.2" fill="currentColor" opacity="0.55"/>
              <rect x="4" y="16" width="12" height="2.4" rx="1.2" fill="currentColor" opacity="0.3"/>
            </svg>
            <span>inlinr<span className="pv-dot">.</span></span>
          </a>
          <span className="pv-sep" />
          <span className="pv-title">{data.campaignTitle || "Email preview"}</span>
        </div>

        <div className="pv-header-center">
          <div className="pv-device-switch">
            {PREVIEW_DEVICES.map(d => (
              <button key={d.id}
                className={device === d.id ? "is-active" : ""}
                onClick={() => setDevice(d.id)}
                title={`${d.label} (${d.width}px)`}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  {d.id === "desktop" && <><rect x="3" y="4" width="18" height="13" rx="2"/><path d="M8 21h8M12 17v4"/></>}
                  {d.id === "tablet" && <><rect x="5" y="3" width="14" height="18" rx="2.5"/><path d="M11 18h2"/></>}
                  {d.id === "mobile" && <><rect x="7" y="2" width="10" height="20" rx="2.5"/><path d="M11 18h2"/></>}
                </svg>
                <span>{d.label}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="pv-header-right">
          <button className={`pv-dark-btn${darkMode ? " is-on" : ""}`}
            onClick={() => setDarkMode(d => !d)}
            title="Toggle dark mode">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              {darkMode
                ? <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></>
                : <path d="M21 13A9 9 0 0 1 11 3a7 7 0 1 0 10 10z"/>}
            </svg>
            <span>{darkMode ? "Light" : "Dark"}</span>
          </button>
          {expiresAt && (
            <span className="pv-expires">
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>
              </svg>
              Expires {expiresAt.toLocaleDateString("en-US", { month: "short", day: "numeric" })}
            </span>
          )}
        </div>
      </header>

      <div className={`pv-viewport${darkMode ? " is-dark" : ""}`}>
        <div className={`pv-device pv-device--${device}`}>
          {device === "tablet" && (
            <div className="pv-bezel-top">
              <div className="pv-bezel-cam" />
            </div>
          )}
          {device === "mobile" && (
            <div className="pv-bezel-top">
              <div className="pv-notch" />
            </div>
          )}
          <div className="pv-screen" style={{ width: currentDevice.width }}>
            <iframe
              ref={iframeRef}
              title="Email preview"
              sandbox="allow-same-origin"
              className="pv-iframe"
            />
          </div>
          {device === "tablet" && (
            <div className="pv-bezel-bottom">
              <div className="pv-home-bar" />
            </div>
          )}
          {device === "mobile" && (
            <div className="pv-bezel-bottom">
              <div className="pv-home-bar" />
            </div>
          )}
        </div>
      </div>

      <footer className="pv-footer">
        <a href="/" className="pv-brand-link">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <rect x="4" y="6" width="14" height="2.4" rx="1.2" fill="currentColor"/>
            <rect x="4" y="11" width="9" height="2.4" rx="1.2" fill="currentColor" opacity="0.55"/>
            <rect x="4" y="16" width="12" height="2.4" rx="1.2" fill="currentColor" opacity="0.3"/>
          </svg>
          Powered by Inlinr
        </a>
      </footer>
    </div>
  );
};

Object.assign(window, { PreviewPage });
