// =====================================================
// TACTICAL OPS PORTFOLIO — main app
// Boot screen, HUD, particle background, crosshair, nav
// =====================================================

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

// ---------- DATA ----------
const SECTIONS = [
  { id: 'bio',      tag: '01', label: '// profile',  title: 'Operator Profile',     dot: 'var(--gold)' },
  { id: 'exp',      tag: '02', label: '// deploy',   title: 'Deployment History',   dot: 'var(--blue)' },
  { id: 'edu',      tag: '03', label: '// boot',     title: 'Training Ground',      dot: 'var(--orange)' },
  { id: 'arsenal',  tag: '04', label: '// arsenal',  title: 'Arsenal Loadout',      dot: 'var(--green)' },
  { id: 'projects', tag: '05', label: '// intel',    title: 'Mission Briefing',     dot: 'var(--purple)' },
  { id: 'report',   tag: '06', label: '// report',   title: 'Operation Report',     dot: '#cfd6dd' },
  { id: 'live',     tag: '07', label: '// live',     title: 'Live Feed',            dot: 'var(--red)' },
];

// Radar dot positions (relative to 70px square, percentage)
const RADAR_POS = [
  [30, 26], [62, 32], [44, 50], [22, 60], [70, 58], [38, 76], [60, 78]
];

// ---------- CROSSHAIR ----------
function Crosshair() {
  const ref = useRef(null);
  useEffect(() => {
    document.documentElement.style.cursor = 'none';
    document.body.style.cursor = 'none';
    const onMove = (e) => {
      if (ref.current) {
        ref.current.style.transform = `translate(${e.clientX}px, ${e.clientY}px) translate(-50%, -50%)`;
      }
    };
    const onLeave = () => {
      document.body.classList.add('mouse-outside');
      document.documentElement.style.cursor = '';
      document.body.style.cursor = '';
    };
    const onEnter = () => {
      document.body.classList.remove('mouse-outside');
      document.documentElement.style.cursor = 'none';
      document.body.style.cursor = 'none';
    };
    window.addEventListener('mousemove', onMove, { passive: true });
    document.documentElement.addEventListener('mouseleave', onLeave);
    document.documentElement.addEventListener('mouseenter', onEnter);
    return () => {
      window.removeEventListener('mousemove', onMove);
      document.documentElement.removeEventListener('mouseleave', onLeave);
      document.documentElement.removeEventListener('mouseenter', onEnter);
    };
  }, []);
  return (
    <div className="crosshair" ref={ref}>
      <span></span><span></span>
      <span className="dot"></span>
    </div>
  );
}

// ---------- TACTICAL TOUR ----------
const TOUR_STEPS = [
  {
    target: null,
    title: 'WELCOME — OPERATOR BRIEFING',
    desc: 'This portfolio uses a Counter-Strike tactical theme. Sections are "missions", skills are "weapons", work history is "deployment history". Take 30 seconds to learn how to navigate.',
  },
  {
    target: '.radar',
    title: 'RADAR · NAVIGATION',
    desc: 'Mini-map of the site. Each dot = one section. Active section glows gold. Click any dot to fast-travel — or use ↑↓ arrow keys to scroll between sections.',
    side: 'right',
  },
  {
    target: '.nav-links',
    title: 'SECTION SHORTCUTS',
    desc: '01 Profile · 02 Work History · 03 Education · 04 Skills · 05 Projects · 06 Achievements · 07 Live Feed. Click any link to jump there instantly.',
    side: 'right',
  },
  {
    target: '.console-hint',
    title: 'COMMAND CONSOLE',
    desc: 'Press ~ (tilde key, top-left of keyboard) to open a fully functional terminal. Try typing: "whoami", "status", "skills", or "jump arsenal".',
  },
  {
    target: null,
    title: 'CLICK ANYWHERE · IMPACT FX',
    desc: 'Click on any empty background area to fire. Bullet impacts, sparks, and sonar rings are available — use the Tweaks panel (bottom-right ▲ corner) to switch modes and change the accent color.',
  },
];

function TacticalTour({ onOpenTour, tourOpen, setTourOpen }) {
  const [step, setStep] = useState(0);
  const [rect, setRect] = useState(null);

  useEffect(() => {
    if (!tourOpen) return;
    const current = TOUR_STEPS[step];
    if (current.target) {
      const el = document.querySelector(current.target);
      if (el) {
        const r = el.getBoundingClientRect();
        setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
      } else {
        setRect(null);
      }
    } else {
      setRect(null);
    }
  }, [tourOpen, step]);

  const next = () => {
    if (step < TOUR_STEPS.length - 1) {
      setStep(s => s + 1);
    } else {
      close();
    }
  };
  const prev = () => step > 0 && setStep(s => s - 1);
  const close = () => {
    setTourOpen(false);
    localStorage.setItem('tour_seen_v1', '1');
  };

  const current = TOUR_STEPS[step];
  const PAD = 10;

  const tooltipStyle = () => {
    if (!rect) return { top: '50%', left: '50%', transform: 'translate(-50%,-50%)' };
    const { top, left, width, height } = rect;
    const side = current.side || 'left';
    const VW = window.innerWidth;
    const VH = window.innerHeight;
    const TW = 370, TH = 240;
    const clampY = (y) => Math.max(TH / 2 + 8, Math.min(y, VH - TH / 2 - 8));
    const clampX = (x) => Math.max(TW / 2 + 8, Math.min(x, VW - TW / 2 - 8));
    if (side === 'right') {
      const tipLeft = Math.min(left + width + 18, VW - TW - 8);
      return { top: clampY(top + height / 2), left: tipLeft, transform: 'translateY(-50%)' };
    }
    if (side === 'bottom') {
      return { top: Math.min(top + height + 14, VH - TH - 8), left: clampX(left + width / 2), transform: 'translateX(-50%)' };
    }
    if (side === 'top') {
      return { bottom: Math.max(VH - top + 14, TH + 8), left: clampX(left + width / 2), transform: 'translateX(-50%)' };
    }
    const tipRight = VW - left + 18;
    return { top: clampY(top + height / 2), right: Math.max(tipRight, TW + 8), transform: 'translateY(-50%)' };
  };

  if (!tourOpen) {
    return (
      <button className="tour-trigger" onClick={onOpenTour} title="Site guide — how to navigate">
        ?
      </button>
    );
  }

  return (
    <>
      {rect ? (
        <>
          <div className="tour-click-catcher" onClick={close} />
          <div
            className="tour-spotlight"
            style={(() => {
              const EDGE = 2;
              const sl = Math.max(EDGE, rect.left - PAD);
              const st = Math.max(EDGE, rect.top - PAD);
              const sr = Math.min(window.innerWidth - EDGE, rect.left + rect.width + PAD);
              const sb = Math.min(window.innerHeight - EDGE, rect.top + rect.height + PAD);
              return { top: st, left: sl, width: sr - sl, height: sb - st };
            })()}
          />
        </>
      ) : (
        <div className="tour-dim" onClick={close} />
      )}
      <div className="tour-tip" style={tooltipStyle()} onClick={e => e.stopPropagation()}>
        <div className="tour-step-count">STEP {step + 1} / {TOUR_STEPS.length}</div>
        <div className="tour-title">{current.title}</div>
        <div className="tour-desc">{current.desc}</div>
        <div className="tour-buttons">
          {step > 0 && <button className="tour-btn secondary" onClick={prev}>← BACK</button>}
          <button className="tour-btn skip" onClick={close}>SKIP</button>
          <button className="tour-btn primary" onClick={next}>
            {step === TOUR_STEPS.length - 1 ? 'DONE ✓' : 'NEXT →'}
          </button>
        </div>
      </div>
    </>
  );
}

// ---------- BOOT SCREEN ----------
const BOOT_LINES = [
  'Connecting to ops/portfolio.v2 ...',
  'Loading operator credentials ...',
  'Initialising render engine ...',
  'Parsing skill manifest ... OK',
  'Mounting deployment history ... OK',
  'Loading mission intel ... OK',
  'Starting live feed ... OK',
  'Welcome, recruiter.',
];

function Boot({ onDone }) {
  const [hide, setHide] = useState(false);
  const [done, setDone] = useState(false);
  const [visibleLines, setVisibleLines] = useState(0);

  useEffect(() => {
    const timers = [];
    BOOT_LINES.forEach((_, i) => {
      timers.push(setTimeout(() => setVisibleLines(v => Math.max(v, i + 1)), 800 + i * 220));
    });
    timers.push(setTimeout(() => setHide(true), 4400));
    timers.push(setTimeout(() => { setDone(true); onDone && onDone(); }, 5100));
    return () => timers.forEach(clearTimeout);
  }, []);

  useEffect(() => {
    const skip = (e) => {
      if (e.type === 'click' || e.key === 'Escape') {
        setHide(true);
        setTimeout(() => { setDone(true); onDone && onDone(); }, 600);
      }
    };
    window.addEventListener('click', skip);
    window.addEventListener('keydown', skip);
    return () => {
      window.removeEventListener('click', skip);
      window.removeEventListener('keydown', skip);
    };
  }, []);

  if (done) return null;
  return (
    <div className={`boot ${hide ? 'hide' : ''}`}>
      <div className="logo">OPERATOR</div>
      <div className="sub">portfolio · v2.0 · initialising</div>
      <div className="term">
        {BOOT_LINES.slice(0, visibleLines).map((line, i) => {
          const okMatch = line.match(/(.*?)( OK)$/);
          return (
            <div className="term-line" key={i} style={{ animationDelay: '0s' }}>
              <span className="arrow">&gt; </span>
              {okMatch ? (
                <>{okMatch[1]}<span className="ok">{okMatch[2]}</span></>
              ) : line}
            </div>
          );
        })}
      </div>
      <div className="progress"></div>
      <div className="skip">[ CLICK OR ESC TO SKIP ]</div>
    </div>
  );
}

// ---------- HUD TOP ----------
function HudTop() {
  return (
    <div className="hud-top">
      <div className="left">
        <span className="name">VISHESH CHAITANYA</span>
        <span className="sep">//</span>
        <span className="role">SENIOR SOFTWARE ENGINEER</span>
      </div>
      <div className="center">
        <span>ops/portfolio.v2</span>
        <span className="ping"><span className="dot"></span>ONLINE · 8ms</span>
      </div>
      <div className="right">
        <span className="console-hint">press <kbd>~</kbd> to open console</span>
      </div>
    </div>
  );
}

function SvgGithub() {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 .5C5.4.5 0 5.9 0 12.5c0 5.3 3.4 9.8 8.2 11.4.6.1.8-.3.8-.6v-2c-3.3.7-4-1.6-4-1.6-.5-1.4-1.3-1.8-1.3-1.8-1.1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1.1 1.8 2.8 1.3 3.5 1 .1-.8.4-1.3.8-1.6-2.7-.3-5.5-1.3-5.5-6 0-1.3.5-2.4 1.2-3.2-.1-.3-.5-1.5.1-3.2 0 0 1-.3 3.3 1.2.9-.3 2-.4 3-.4s2.1.1 3 .4c2.3-1.5 3.3-1.2 3.3-1.2.7 1.7.2 2.9.1 3.2.8.8 1.2 1.9 1.2 3.2 0 4.7-2.8 5.7-5.5 6 .4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6C20.6 22.3 24 17.8 24 12.5 24 5.9 18.6.5 12 .5z"/>
    </svg>
  );
}
function SvgCode() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M8 6l-6 6 6 6M16 6l6 6-6 6"/>
    </svg>
  );
}
function SvgChef() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M6 18c-2 0-4-2-4-4s2-4 4-4c0-3 3-5 6-5s6 2 6 5c2 0 4 2 4 4s-2 4-4 4M8 22h8"/>
    </svg>
  );
}
function SvgIn() {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M4 4h4v4H4zm0 6h4v10H4zM10 10h4v2c.7-1.2 2.2-2.3 4-2.3 3.5 0 4 2.3 4 4.7V20h-4v-5c0-1.3-.5-2.3-1.8-2.3-1.5 0-2.2 1-2.2 2.5V20h-4z"/>
    </svg>
  );
}

// ---------- HUD BOTTOM ----------
const SOCIAL_LINKS = [
  { label: 'GitHub',   href: 'https://github.com/visheshchaitanya',                   icon: <SvgGithub /> },
  { label: 'LinkedIn', href: 'https://www.linkedin.com/in/visheshchaitanya/',         icon: <SvgIn /> },
  { label: 'LeetCode', href: 'https://leetcode.com/u/visheshchaitanya/',              icon: <SvgCode /> },
  { label: 'CodeChef', href: 'https://www.codechef.com/users/visheshc21',             icon: <SvgChef /> },
];

const isMac = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);

function HudBottom({ onConsole }) {
  return (
    <div className="hud-bottom">
      <span className="key-hint"><span className="key">↑↓</span>Scroll</span>
      <span className="key-hint"><span className="key">B</span>Arsenal</span>
      <span className="key-hint"><span className="key">TAB</span>Report</span>
      <span className="key-hint"><button className="key" onClick={onConsole}>~</button>Console</span>
      <span className="key-hint"><button className="key" onClick={() => window.__fxClear?.()}>{isMac ? '⌘' : 'CTRL'}</button>Impacts</span>
      <div className="hud-socials">
        {SOCIAL_LINKS.map(s => (
          <a key={s.label} className="social" href={s.href} target="_blank" rel="noopener noreferrer">
            {s.icon}{s.label}
          </a>
        ))}
      </div>
    </div>
  );
}

// ---------- LEFT NAV ----------
function NavLeft({ active, onJump }) {
  return (
    <div className="nav-left">
      <div className="radar">
        <div className="radar-sweep" />
        {SECTIONS.map((s, i) => (
          <button
            key={s.id}
            className={`radar-dot ${i === active ? 'active' : ''}`}
            style={{
              left: `${RADAR_POS[i][0]}%`,
              top: `${RADAR_POS[i][1]}%`,
              background: i === active ? 'var(--gold)' : s.dot,
              color: i === active ? 'var(--gold)' : s.dot,
              border: 0, padding: 0,
            }}
            onClick={() => onJump(i)}
            aria-label={s.title}
          />
        ))}
      </div>
      <div className="radar-label">RADAR · {String(active + 1).padStart(2, '0')}/{SECTIONS.length}</div>
      <div className="nav-links">
        {SECTIONS.map((s, i) => (
          <button
            key={s.id}
            className={`nav-link ${i === active ? 'active' : ''}`}
            onClick={() => onJump(i)}
          >
            <span className="num">{s.tag}</span>{s.label}
          </button>
        ))}
      </div>
      <div className="nav-footer">
        SYS · OK<br />
        LAT · 8ms<br />
        BUILD · v2.0
      </div>
    </div>
  );
}

// ---------- CONSOLE ----------
function Console({ open, onClose, onCommand }) {
  const [history, setHistory] = useState([
    { type: 'info', text: 'tactical console v2.0 — type "help" for commands' },
  ]);
  const [val, setVal] = useState('');
  const inputRef = useRef(null);
  const outRef = useRef(null);

  useEffect(() => {
    if (open) setTimeout(() => inputRef.current && inputRef.current.focus(), 100);
    else inputRef.current && inputRef.current.blur();
  }, [open]);

  useEffect(() => {
    if (outRef.current) outRef.current.scrollTop = outRef.current.scrollHeight;
  }, [history]);

  const run = (cmd) => {
    const c = cmd.trim().toLowerCase();
    setHistory(h => [...h, { type: 'cmd', text: cmd }]);
    let resp;
    switch (c) {
      case 'help':
        resp = { type: 'out', text: 'available: whoami, status, contact, github, resume, skills, jump <section>, clear' };
        break;
      case 'whoami':
        resp = { type: 'out', text: 'callsign: V1SHESH\nrole: Senior Software Engineer · Backend\ncurrent: QuilrAI (May 2025 – present)\nlocation: Delhi/NCR\nstack: Java · Spring Boot · Kafka · PostgreSQL · Redis · ClickHouse' };
        break;
      case 'status':
        resp = { type: 'ok', text: 'all systems nominal · 8ms latency · particle field stable' };
        break;
      case 'contact':
        resp = { type: 'out', text: 'linkedin → https://www.linkedin.com/in/visheshchaitanya/\nemail → visheshchaitanya@gmail.com' };
        break;
      case 'github':
        resp = { type: 'info', text: '→ https://github.com/visheshchaitanya' };
        break;
      case 'resume':
        resp = { type: 'info', text: 'linkedin → https://www.linkedin.com/in/visheshchaitanya/' };
        break;
      case 'skills':
        resp = { type: 'info', text: 'press B or jump to section 04 — the arsenal.' };
        break;
      case 'clear':
        setHistory([]); setVal(''); return;
      default:
        if (c.startsWith('jump ')) {
          const target = c.slice(5);
          const idx = SECTIONS.findIndex(s => s.id === target || s.label.includes(target));
          if (idx >= 0) { onCommand && onCommand('jump', idx); resp = { type: 'ok', text: `> jumping to ${SECTIONS[idx].title.toLowerCase()}` }; }
          else resp = { type: 'err', text: `unknown section: ${target}` };
        } else {
          resp = { type: 'err', text: `unknown command: ${c} — try "help"` };
        }
    }
    setHistory(h => [...h, resp]);
    setVal('');
  };

  return (
    <div className="console-clip">
      <div className={`console ${open ? 'open' : ''}`}>
        <div className="header">
          <span style={{ color: 'var(--gold)' }}>~ CONSOLE</span>
          <span>ops/portfolio.v2</span>
          <span style={{ marginLeft: 'auto' }}>ESC to close</span>
        </div>
        <div className="out" ref={outRef}>
          {history.map((h, i) => (
            <div className={`line ${h.type === 'err' ? 'err' : ''} ${h.type === 'info' ? 'info' : ''} ${h.type === 'ok' ? 'ok' : ''}`} key={i}>
              {h.type === 'cmd' ? <><span className="prompt">&gt; </span>{h.text}</> : h.text}
            </div>
          ))}
        </div>
        <div className="input-row">
          <span className="caret">&gt;</span>
          <input
            ref={inputRef}
            value={val}
            onChange={e => setVal(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter' && val.trim()) run(val);
              else if (e.key === 'Escape') onClose();
            }}
            placeholder="type command..."
            autoComplete="off"
          />
        </div>
      </div>
    </div>
  );
}

// Export to window so sections.jsx can reach things if needed
window.__app = { SECTIONS, RADAR_POS };
Object.assign(window, {
  Crosshair, Boot, HudTop, HudBottom, NavLeft, Console, SECTIONS, TacticalTour
});
