"use client";

import { useEffect, useRef, useState } from "react";
import {
  IconBell,
  IconBox,
  IconCheck,
  IconFile,
} from "@/components/icons";
import { site } from "@/lib/site";

const TABS = [
  { id: "t-1", panel: "pt-1", label: "Real-time", letter: "A" },
  { id: "t-2", panel: "pt-2", label: "Scripts & fileless", letter: "B" },
  { id: "t-3", panel: "pt-3", label: "Ransomware", letter: "C" },
  { id: "t-4", panel: "pt-4", label: "Quarantine", letter: "D" },
] as const;

const DURATION = 7000;

export function ProtectionTabs() {
  const wrapRef = useRef<HTMLDivElement>(null);
  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const [visible, setVisible] = useState(false);
  const [progressKey, setProgressKey] = useState(0);

  useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap || !("IntersectionObserver" in window)) {
      setVisible(true);
      return;
    }
    const io = new IntersectionObserver(
      (entries) => setVisible(Boolean(entries[0]?.isIntersecting)),
      { threshold: 0.3 },
    );
    io.observe(wrap);
    return () => io.disconnect();
  }, []);

  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce || paused || !visible) return;
    const timer = window.setInterval(() => {
      setIdx((i) => (i + 1) % TABS.length);
      setProgressKey((k) => k + 1);
    }, DURATION);
    return () => window.clearInterval(timer);
  }, [paused, visible]);

  useEffect(() => {
    // The active tab is re-keyed on selection, so measure after the remount has laid out.
    const raf = requestAnimationFrame(() => {
      const list = wrapRef.current?.querySelector<HTMLElement>(".ptab-list");
      const btn = wrapRef.current?.querySelectorAll<HTMLButtonElement>("[data-tab]")[idx];
      if (!list || !btn) return;

      const maxScroll = list.scrollWidth - list.clientWidth;
      if (maxScroll <= 0) return;

      const listRect = list.getBoundingClientRect();
      const btnRect = btn.getBoundingClientRect();
      if (!btnRect.width) return;

      const offsetWithinList = btnRect.left - listRect.left;
      const centered =
        list.scrollLeft + offsetWithinList - (list.clientWidth - btnRect.width) / 2;

      const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      list.scrollTo({
        left: Math.max(0, Math.min(centered, maxScroll)),
        behavior: reduce ? "auto" : "smooth",
      });
    });

    return () => cancelAnimationFrame(raf);
  }, [idx]);

  function select(n: number, focus = false) {
    const next = ((n % TABS.length) + TABS.length) % TABS.length;
    setIdx(next);
    setProgressKey((k) => k + 1);
    if (focus) {
      const btn = wrapRef.current?.querySelectorAll<HTMLButtonElement>("[data-tab]")[next];
      btn?.focus({ preventScroll: true });
    }
  }

  return (
    <div
      className={`ptabs${paused ? " is-paused" : ""}`}
      data-tabs
      ref={wrapRef}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      <div className="ptab-list" role="tablist" aria-label="Protection layers">
        {TABS.map((tab, n) => {
          const on = n === idx;
          return (
            <button
              key={on ? `${tab.id}-${progressKey}` : tab.id}
              className={`ptab${on ? " is-on" : ""}`}
              role="tab"
              aria-selected={on}
              aria-controls={tab.panel}
              id={tab.id}
              data-tab
              tabIndex={on ? 0 : -1}
              type="button"
              onClick={() => select(n)}
              onKeyDown={(e) => {
                if (e.key === "ArrowDown" || e.key === "ArrowRight") {
                  e.preventDefault();
                  select(idx + 1, true);
                }
                if (e.key === "ArrowUp" || e.key === "ArrowLeft") {
                  e.preventDefault();
                  select(idx - 1, true);
                }
              }}
            >
              <span className="ptab-n">{tab.letter}</span>
              {tab.label}
            </button>
          );
        })}
      </div>

      <div className="ptab-panels">
        <div
          className={`ptab-panel${idx === 0 ? " is-on" : ""}`}
          role="tabpanel"
          id="pt-1"
          aria-labelledby="t-1"
          hidden={idx !== 0}
        >
          <div className="panel-copy">
            <h3>There when you need it. Invisible when you don&apos;t</h3>
            <p>
              {site.name} is designed to keep protection running quietly in the
              background so security doesn&apos;t become another thing you have to
              remember.
            </p>
            <ul className="ticks">
              <li>
                <IconCheck />
                Runs in the background
              </li>
              <li>
                <IconCheck />
                Responds as things happen
              </li>
              <li>
                <IconCheck />
                Keeps interruptions meaningful
              </li>
            </ul>
          </div>
          <div className="panel-visual">
            <div className="mock">
              <div className="mock-head">
                <strong>Live file activity</strong>
                <span className="tag tag-ok">
                  <i></i>Monitoring
                </span>
              </div>
              <div className="file-row">
                <span className="fi">
                  <IconFile />
                </span>
                <span className="fn">
                  Quarterly_report.xlsx
                  <small>Opened · Downloads</small>
                </span>
                <em className="ok">Safe</em>
              </div>
              <div className="file-row is-bad">
                <span className="fi">
                  <IconFile />
                </span>
                <span className="fn">
                  setup_x64.exe
                  <small>Launch attempt · Temp</small>
                </span>
                <em className="bad">Blocked</em>
              </div>
              <div className="file-row">
                <span className="fi">
                  <IconFile />
                </span>
                <span className="fn">
                  holiday_photos.zip
                  <small>Saved · Desktop</small>
                </span>
                <em className="ok">Safe</em>
              </div>
            </div>
          </div>
        </div>

        <div
          className={`ptab-panel${idx === 1 ? " is-on" : ""}`}
          role="tabpanel"
          id="pt-2"
          aria-labelledby="t-2"
          hidden={idx !== 1}
        >
          <div className="panel-copy">
            <h3>The file is only one part of the story</h3>
            <p>
              Modern attacks can use scripts, processes, and memory instead of
              a suspicious-looking file. {site.name} can look at the activity
              around a potential threat.
            </p>
            <ul className="ticks">
              <li>
                <IconCheck />
                Looks at the intent
              </li>
              <li>
                <IconCheck />
                Works under the surface
              </li>
              <li>
                <IconCheck />
                Sees the bigger picture
              </li>
            </ul>
          </div>
          <div className="panel-visual">
            <div className="term">
              <div className="term-bar">
                <i></i>
                <i></i>
                <i></i>
                <span>PowerShell</span>
              </div>
              <pre>
                <span className="c-dim">PS C:\Users\dana&gt;</span> .\update_helper.ps1
                {"\n"}
                <span className="c-dim">Loading module…</span>
                {"\n"}
                <span className="c-bad">■ {site.name} blocked this script</span>
                {"\n"}
                <span className="c-dim">  reason</span>  hidden download-and-run
                {"\n"}
                <span className="c-dim">  action</span> {" "}
                <span className="c-ok">stopped before execution</span>
              </pre>
            </div>
          </div>
        </div>

        <div
          className={`ptab-panel${idx === 2 ? " is-on" : ""}`}
          role="tabpanel"
          id="pt-3"
          aria-labelledby="t-3"
          hidden={idx !== 2}
        >
          <div className="panel-copy">
            <h3>Your files should be only yours.</h3>
            <p>
              {site.name} identifies suspicious behavior early and brings it to
              your attention before it becomes something you have to untangle.
            </p>
            <ul className="ticks">
              <li>
                <IconCheck />
                Watches for unusual behavior
              </li>
              <li>
                <IconCheck />
                Protects what matters
              </li>
              <li>
                <IconCheck />
                Helps you act before the damage spreads
              </li>
            </ul>
          </div>
          <div className="panel-visual">
            <div className="mock">
              <div className="mock-head">
                <strong>Behaviour monitor</strong>
                <span className="tag tag-bad">1 stopped</span>
              </div>
              <div className="tree">
                <div className="node">
                  <i className="ok"></i>explorer.exe
                </div>
                <div className="node l1">
                  <i className="ok"></i>winword.exe
                </div>
                <div className="node l2">
                  <i className="warn"></i>cmd.exe<small>unusual</small>
                </div>
                <div className="node l3 is-bad">
                  <i className="bad"></i>locker.exe<small>terminated</small>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div
          className={`ptab-panel${idx === 3 ? " is-on" : ""}`}
          role="tabpanel"
          id="pt-4"
          aria-labelledby="t-4"
          hidden={idx !== 3}
        >
          <div className="panel-copy">
            <h3>A safer place for questionable files.</h3>
            <p>
              {site.name} is built in such a way that it helps separate out
              suspicious objects but ensures that the relevant information
              remains easily accessible.
            </p>
            <ul className="ticks">
              <li>
                <IconCheck />
                Separates suspicious objects
              </li>
              <li>
                <IconCheck />
                Preserves information for review
              </li>
              <li>
                <IconCheck />
                Helps in restoration or elimination
              </li>
            </ul>
          </div>
          <div className="panel-visual">
            <div className="mock">
              <div className="mock-head">
                <strong>Quarantine</strong>
                <small>2 items</small>
              </div>
              <div className="file-row">
                <span className="fi">
                  <IconBox />
                </span>
                <span className="fn">
                  invoice_0917.js
                  <small>Script threat · today</small>
                </span>
                <button type="button" className="mini-btn">
                  Restore
                </button>
              </div>
              <div className="file-row">
                <span className="fi">
                  <IconBox />
                </span>
                <span className="fn">
                  setup_x64.exe
                  <small>Malware · today</small>
                </span>
                <button type="button" className="mini-btn">
                  Restore
                </button>
              </div>
              <div className="notify">
                <IconBell />
                <span>
                  <strong>my_build_tool.exe allowed</strong>
                  <small>Added to trusted apps</small>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
