// Main App

function ActivityBar({ active, onSelect, onTogglePalette }) {
  const icons = [
    { id: 'explorer', title: 'Explorer', svg: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 5h6l2 2h10v12H3z"/></svg>
    )},
    { id: 'search', title: 'Search', svg: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/></svg>
    )},
    { id: 'git', title: 'Source Control', svg: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="12" r="2"/><path d="M6 8v8M8 6h4a4 4 0 0 1 4 4v0"/></svg>
    )},
    { id: 'skills', title: 'Skills Dashboard', svg: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 20V10M10 20V4M16 20v-8M22 20H2"/></svg>
    )},
    { id: 'terminal', title: 'Toggle Terminal', svg: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="2.5" y="4" width="19" height="16" rx="2"/><path d="M6 10l3 2-3 2M12 14h5"/></svg>
    )},
  ];
  const bottom = [
    { id: 'palette', title: 'Command Palette (⌘K)', onClick: onTogglePalette, svg: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M6 8l-3 4 3 4M18 8l3 4-3 4M14 4l-4 16"/></svg>
    )},
    { id: 'settings', title: 'Tweaks', svg: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="3"/><path d="M12 2v3m0 14v3M2 12h3m14 0h3M4.9 4.9l2.1 2.1m10 10l2.1 2.1M4.9 19.1l2.1-2.1m10-10l2.1-2.1"/></svg>
    )},
  ];
  return (
    <div className="activity">
      {icons.map(ic => (
        <button
          key={ic.id}
          className={`act-btn ${active === ic.id ? 'active' : ''}`}
          title={ic.title}
          onClick={() => onSelect(ic.id)}
        >
          {ic.svg}
        </button>
      ))}
      <div className="spacer" />
      {bottom.map(ic => (
        <button
          key={ic.id}
          className="act-btn"
          title={ic.title}
          onClick={() => ic.onClick ? ic.onClick() : onSelect(ic.id)}
        >
          {ic.svg}
        </button>
      ))}
    </div>
  );
}

function CommandPalette({ open, onClose, onOpenFile, commands }) {
  const [q, setQ] = useState('');
  const [idx, setIdx] = useState(0);
  const inputRef = useRef(null);
  useEffect(() => { if (open && inputRef.current) inputRef.current.focus(); if (open) { setQ(''); setIdx(0); } }, [open]);

  const filtered = useMemo(() => {
    if (!q) return commands.slice(0, 20);
    const qq = q.toLowerCase();
    return commands.filter(c => (c.label + ' ' + (c.kind || '')).toLowerCase().includes(qq)).slice(0, 20);
  }, [q, commands]);

  useEffect(() => { setIdx(0); }, [q]);

  if (!open) return null;

  const run = (c) => {
    if (c.action) c.action();
    else if (c.path) onOpenFile(c.path);
    onClose();
  };

  return (
    <div className="palette-bg" onClick={onClose}>
      <div className="palette" onClick={(e) => e.stopPropagation()}>
        <input
          ref={inputRef}
          placeholder="Type a file name, '>' for commands…"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Escape') onClose();
            else if (e.key === 'ArrowDown') { e.preventDefault(); setIdx(i => Math.min(filtered.length - 1, i + 1)); }
            else if (e.key === 'ArrowUp') { e.preventDefault(); setIdx(i => Math.max(0, i - 1)); }
            else if (e.key === 'Enter') { if (filtered[idx]) run(filtered[idx]); }
          }}
        />
        <div className="list">
          {filtered.map((c, i) => (
            <div key={c.id} className={`prow ${i === idx ? 'active' : ''}`} onClick={() => run(c)}>
              {c.glyph}
              <span>{c.label}</span>
              <span className="kind">{c.kind}</span>
            </div>
          ))}
          {filtered.length === 0 && <div className="prow"><span className="kind">No matches</span></div>}
        </div>
      </div>
    </div>
  );
}

function TweaksPanel({ open, theme, setTheme, font, setFont, terminalVisible, setTerminalVisible, onClose }) {
  if (!open) return null;
  return (
    <div className="tweaks open">
      <div className="tweaks-header">
        <strong>Tweaks</strong>
        <button onClick={onClose} style={{ color: 'var(--text-dim)', fontSize: 14 }}>×</button>
      </div>
      <div className="tweaks-body">
        <div className="tweak-row">
          <label>Color Theme</label>
          <div className="opts">
            {['dark', 'light', 'nocturne'].map(t => (
              <button key={t} className={`opt ${theme === t ? 'active' : ''}`} onClick={() => setTheme(t)}>
                {t === 'dark' ? 'Amber Dark' : t === 'light' ? 'Parchment' : 'Nocturne'}
              </button>
            ))}
          </div>
        </div>
        <div className="tweak-row">
          <label>Editor Font</label>
          <div className="opts">
            {['JetBrains Mono', 'SF Mono', 'IBM Plex Mono'].map(f => (
              <button key={f} className={`opt ${font === f ? 'active' : ''}`} onClick={() => setFont(f)}>
                {f.replace(' Mono', '')}
              </button>
            ))}
          </div>
        </div>
        <div className="tweak-row">
          <label>Terminal</label>
          <div className="opts">
            <button className={`opt ${!terminalVisible ? 'active' : ''}`} onClick={() => setTerminalVisible(false)}>Hide</button>
            <button className={`opt ${terminalVisible ? 'active' : ''}`} onClick={() => setTerminalVisible(true)}>Show</button>
          </div>
        </div>
        <div style={{ fontSize: 11, color: 'var(--text-mute)', fontFamily: 'var(--font-mono)', lineHeight: 1.5 }}>
          Try keyboard shortcuts:<br/>
          ⌘P · file search<br/>
          ⌘K · command palette<br/>
          ⌘J · toggle terminal
        </div>
      </div>
    </div>
  );
}

function StatusBar({ activePath, theme }) {
  const node = activePath ? window.resolveFS(activePath) : null;
  const lang = node?.lang || (node?.type === 'image' ? 'PNG' : 'Welcome');
  const langName = {
    md: 'Markdown',
    json: 'JSON',
    js: 'JavaScript',
    jsx: 'JSX',
    txt: 'Plain Text'
  }[lang] || lang;
  return (
    <div className="statusbar">
      <div className="left">
        <span className="st-item branch">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="12" r="2"/><path d="M6 8v8M8 6h4a4 4 0 0 1 4 4v0"/></svg>
          main
        </span>
        <span className="st-item">⟲ 0 ↑ 0</span>
        <span className="st-item">✓ 0 errors</span>
        <span className="st-item">ⓘ 0 warnings</span>
      </div>
      <div className="spacer" />
      <div className="right">
        <span className="st-item">Ln 1, Col 1</span>
        <span className="st-item">Spaces: 2</span>
        <span className="st-item">UTF-8</span>
        <span className="st-item">LF</span>
        <span className="st-item">{langName}</span>
        <span className="live">open to work</span>
      </div>
    </div>
  );
}

function App() {
  // Tweaks
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "theme": "dark",
    "font": "JetBrains Mono",
    "terminalVisible": true,
    "initialFile": "welcome"
  }/*EDITMODE-END*/;

  const [theme, setTheme] = useState(() => localStorage.getItem('lh_theme') || TWEAK_DEFAULTS.theme);
  const [font, setFont] = useState(() => localStorage.getItem('lh_font') || TWEAK_DEFAULTS.font);
  const [terminalVisible, setTerminalVisible] = useState(() => {
    const s = localStorage.getItem('lh_term'); return s === null ? TWEAK_DEFAULTS.terminalVisible : s === 'true';
  });
  const [terminalCollapsed, setTerminalCollapsed] = useState(false);
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [paletteOpen, setPaletteOpen] = useState(false);
  const [activity, setActivity] = useState('explorer');

  const [tabs, setTabs] = useState(() => {
    const saved = JSON.parse(localStorage.getItem('lh_tabs') || '[]');
    return saved.length ? saved : ['/README.md'];
  });
  const [activePath, setActivePath] = useState(() => {
    return localStorage.getItem('lh_active') || (tabs[0] || null);
  });
  const [openFolders, setOpenFolders] = useState(() => {
    const saved = JSON.parse(localStorage.getItem('lh_folders') || 'null');
    if (saved) return new Set(saved);
    return new Set(['/projects']);
  });
  const [mdViewMode, setMdViewMode] = useState(() => localStorage.getItem('lh_md') || 'preview');

  // Persist
  useEffect(() => { localStorage.setItem('lh_theme', theme); document.documentElement.dataset.theme = theme; }, [theme]);
  useEffect(() => { localStorage.setItem('lh_font', font); document.documentElement.style.setProperty('--font-mono', `'${font}', 'JetBrains Mono', monospace`); }, [font]);
  useEffect(() => { localStorage.setItem('lh_term', terminalVisible); }, [terminalVisible]);
  useEffect(() => { localStorage.setItem('lh_tabs', JSON.stringify(tabs)); }, [tabs]);
  useEffect(() => { localStorage.setItem('lh_active', activePath || ''); }, [activePath]);
  useEffect(() => { localStorage.setItem('lh_folders', JSON.stringify([...openFolders])); }, [openFolders]);
  useEffect(() => { localStorage.setItem('lh_md', mdViewMode); }, [mdViewMode]);

  const openFile = (path) => {
    if (path === 'welcome') { setActivePath(null); return; }
    const node = window.resolveFS(path);
    if (!node) return;
    if (node.type === 'folder') {
      setOpenFolders(prev => {
        const s = new Set(prev);
        if (s.has(path)) s.delete(path); else s.add(path);
        return s;
      });
      return;
    }
    if (!tabs.includes(path)) setTabs(t => [...t, path]);
    setActivePath(path);
    // Also open parent folders
    const parts = path.split('/').filter(Boolean);
    let cur = '';
    const newOpen = new Set(openFolders);
    for (let i = 0; i < parts.length - 1; i++) {
      cur += '/' + parts[i];
      newOpen.add(cur);
    }
    setOpenFolders(newOpen);
  };

  const closeTab = (path) => {
    setTabs(t => {
      const idx = t.indexOf(path);
      const next = t.filter(p => p !== path);
      if (activePath === path) {
        setActivePath(next[Math.max(0, idx - 1)] || null);
      }
      return next;
    });
  };

  const toggleFolder = (path) => {
    setOpenFolders(prev => {
      const s = new Set(prev);
      if (s.has(path)) s.delete(path); else s.add(path);
      return s;
    });
  };

  // Keyboard shortcuts
  useEffect(() => {
    const onKey = (e) => {
      const cmd = e.metaKey || e.ctrlKey;
      if (cmd && (e.key === 'p' || e.key === 'P') && !e.shiftKey) {
        e.preventDefault(); setPaletteOpen(v => !v);
      } else if (cmd && (e.key === 'k' || e.key === 'K')) {
        e.preventDefault(); setPaletteOpen(v => !v);
      } else if (cmd && (e.key === 'j' || e.key === 'J')) {
        e.preventDefault();
        setTerminalVisible(v => !v);
      } else if (cmd && (e.key === 'w' || e.key === 'W')) {
        e.preventDefault(); if (activePath) closeTab(activePath);
      } else if (e.key === 'Escape') {
        setPaletteOpen(false);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [activePath, tabs]);

  // Build palette commands
  const commands = useMemo(() => {
    const out = [];
    // Files
    const walk = (node, path) => {
      if (node.type === 'folder') {
        Object.entries(node.children).forEach(([k, c]) => walk(c, path + '/' + k));
      } else {
        out.push({
          id: 'f:' + path,
          label: path,
          kind: node.lang || node.type,
          path,
          glyph: node.type === 'image' ? window.Glyph.img() : window.Glyph.md()
        });
      }
    };
    Object.entries(window.FS.profile.children).forEach(([k, c]) => walk(c, '/' + k));
    // Commands
    out.push(
      { id: 'c:welcome', label: '> Go to Welcome', kind: 'command', action: () => setActivePath(null), glyph: <span className="glyph">▸</span> },
      { id: 'c:skills', label: '> Open Skills Dashboard', kind: 'command', action: () => { setActivity('skills'); setActivePath('__skills__'); }, glyph: <span className="glyph">▸</span> },
      { id: 'c:theme-dark', label: '> Theme: Amber Dark', kind: 'command', action: () => setTheme('dark'), glyph: <span className="glyph">▸</span> },
      { id: 'c:theme-light', label: '> Theme: Parchment', kind: 'command', action: () => setTheme('light'), glyph: <span className="glyph">▸</span> },
      { id: 'c:theme-noc', label: '> Theme: Nocturne', kind: 'command', action: () => setTheme('nocturne'), glyph: <span className="glyph">▸</span> },
      { id: 'c:term', label: '> Toggle Terminal', kind: 'command', action: () => setTerminalVisible(v => !v), glyph: <span className="glyph">▸</span> },
      { id: 'c:gh', label: '> Open GitHub Profile', kind: 'command', action: () => window.open(window.PORTFOLIO_DATA.profile.social.github, '_blank'), glyph: <span className="glyph">▸</span> },
      { id: 'c:li', label: '> Open LinkedIn', kind: 'command', action: () => window.open(window.PORTFOLIO_DATA.profile.social.linkedin, '_blank'), glyph: <span className="glyph">▸</span> },
      { id: 'c:mail', label: '> Send Email', kind: 'command', action: () => window.open('mailto:' + window.PORTFOLIO_DATA.profile.email, '_blank'), glyph: <span className="glyph">▸</span> },
    );
    return out;
  }, []);

  // Tweaks parent-messaging
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setTweaksOpen(true);
      if (d.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);
  const applyTweak = (key, val) => {
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*'); } catch {}
  };

  // Render main content
  const renderContent = () => {
    if (activity === 'skills' && activePath === '__skills__') return <window.SkillsView />;
    if (!activePath) return <window.WelcomeView onOpen={openFile} />;
    const node = window.resolveFS(activePath);
    if (!node) return <window.WelcomeView onOpen={openFile} />;
    if (node.type === 'image') return <window.ImageView src={node.src} alt={node.title} />;
    const text = node.render();
    if (node.lang === 'md') {
      return (
        <>
          <div className="view-toggle">
            <button className={mdViewMode === 'code' ? 'active' : ''} onClick={() => setMdViewMode('code')}>Source</button>
            <button className={mdViewMode === 'preview' ? 'active' : ''} onClick={() => setMdViewMode('preview')}>Preview</button>
          </div>
          {mdViewMode === 'code'
            ? <window.CodeView text={text} lang="md" onLinkClick={openFile} />
            : <window.PreviewView text={text} />
          }
        </>
      );
    }
    return <window.CodeView text={text} lang={node.lang || 'txt'} onLinkClick={openFile} />;
  };

  const showTabs = activePath && activePath !== '__skills__';

  return (
    <div id="app">
      <div className="titlebar">
        <div className="menus">
          <button>File</button>
          <button>Edit</button>
          <button>View</button>
          <button>Go</button>
          <button>Help</button>
        </div>
        <div className="title">
          <strong>leyder-herrera</strong> — portfolio · press <kbd>⌘K</kbd> to navigate
        </div>
        <div className="window-ctrls">
          <span className="dot amb" />
          <span className="dot grn" />
          <span className="dot red" />
        </div>
      </div>

      <div className="main">
        <ActivityBar
          active={activity}
          onSelect={(id) => {
            setActivity(id);
            if (id === 'skills') setActivePath('__skills__');
            if (id === 'terminal') setTerminalVisible(v => !v);
            if (id === 'settings') setTweaksOpen(v => !v);
          }}
          onTogglePalette={() => setPaletteOpen(v => !v)}
        />
        <window.Sidebar
          activePath={activePath}
          openFolders={openFolders}
          onOpen={openFile}
          onToggleFolder={toggleFolder}
        />

        <div className="editor">
          {showTabs ? (
            <window.Tabs tabs={tabs} activePath={activePath} onSelect={setActivePath} onClose={closeTab} />
          ) : (
            <div className="tabs">
              <div className={`tab active`}>
                {window.Glyph.md()}
                <span>{activity === 'skills' ? 'Skills Dashboard' : 'Welcome'}</span>
              </div>
            </div>
          )}
          {activePath && activePath !== '__skills__' ? (
            <window.Breadcrumbs path={activePath} />
          ) : (
            <div className="breadcrumbs"><span className="crumb">leyder-herrera</span><span className="sep">›</span><span className="crumb">{activity === 'skills' ? 'skills.dashboard' : 'welcome'}</span></div>
          )}
          <div className="content">
            {renderContent()}
          </div>
          {terminalVisible && (
            <window.Terminal
              collapsed={terminalCollapsed}
              onToggle={setTerminalCollapsed}
              onOpenFile={openFile}
            />
          )}
        </div>
      </div>

      <StatusBar activePath={activePath} theme={theme} />

      <CommandPalette
        open={paletteOpen}
        onClose={() => setPaletteOpen(false)}
        onOpenFile={openFile}
        commands={commands}
      />

      <TweaksPanel
        open={tweaksOpen}
        theme={theme}
        setTheme={(v) => { setTheme(v); applyTweak('theme', v); }}
        font={font}
        setFont={(v) => { setFont(v); applyTweak('font', v); }}
        terminalVisible={terminalVisible}
        setTerminalVisible={(v) => { setTerminalVisible(v); applyTweak('terminalVisible', v); }}
        onClose={() => setTweaksOpen(false)}
      />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
