// Editor: tabs, code view, preview view, image view

function Tabs({ tabs, activePath, onSelect, onClose }) {
  return (
    <div className="tabs">
      {tabs.map(p => {
        const name = p.split('/').pop();
        const node = resolveFS(p);
        const lang = node?.lang || (node?.type === 'image' ? 'img' : 'txt');
        const glyph =
          node?.type === 'image' ? window.Glyph.img() :
          lang === 'md' ? window.Glyph.md() :
          lang === 'json' ? window.Glyph.json() :
          name === '.gitignore' ? window.Glyph.git() :
          name === 'LICENSE' ? window.Glyph.lock() :
          window.Glyph.md();
        return (
          <div
            key={p}
            className={`tab ${p === activePath ? 'active' : ''}`}
            onClick={() => onSelect(p)}
          >
            {glyph}
            <span>{name}</span>
            <span className="close" onClick={(e) => { e.stopPropagation(); onClose(p); }}></span>
          </div>
        );
      })}
    </div>
  );
}

function resolveFS(path) {
  const parts = path.split('/').filter(Boolean);
  let node = window.FS.profile;
  for (const p of parts) {
    if (!node || !node.children) return null;
    node = node.children[p];
  }
  return node;
}

function Breadcrumbs({ path }) {
  const parts = ['leyder-herrera', ...path.split('/').filter(Boolean)];
  return (
    <div className="breadcrumbs">
      {parts.map((p, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span className="sep">›</span>}
          <span className="crumb">{p}</span>
        </React.Fragment>
      ))}
    </div>
  );
}

// Simple markdown → HTML for preview
function renderMarkdown(md) {
  const lines = md.split('\n');
  const out = [];
  let i = 0;
  let inList = false;
  const closeList = () => { if (inList) { out.push('</ul>'); inList = false; } };

  const inlineFmt = (s) => {
    s = s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    s = s.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
    s = s.replace(/(^|[^*])\*([^*\n]+?)\*([^*]|$)/g, '$1<em>$2</em>$3');
    s = s.replace(/`([^`]+)`/g, '<code>$1</code>');
    s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g,
      (_, t, u) => {
        if (u.startsWith('http') || u.startsWith('mailto')) {
          return `<a href="${u}" target="_blank" rel="noopener">${t}</a>`;
        }
        return `<a href="${u}">${t}</a>`;
      });
    return s;
  };

  while (i < lines.length) {
    const line = lines[i];
    // Image
    const imgM = line.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
    if (imgM) {
      closeList();
      out.push(`<div class="shot-frame"><img src="${imgM[2]}" alt="${imgM[1]}"/><div class="shot-caption">${imgM[1]}</div></div>`);
      i++; continue;
    }
    // Heading
    const hM = line.match(/^(#{1,6})\s+(.*)$/);
    if (hM) { closeList(); out.push(`<h${hM[1].length}>${inlineFmt(hM[2])}</h${hM[1].length}>`); i++; continue; }
    // HR
    if (/^---+$/.test(line)) { closeList(); out.push('<hr/>'); i++; continue; }
    // Blockquote
    if (/^>\s?/.test(line)) {
      closeList();
      out.push(`<blockquote>${inlineFmt(line.replace(/^>\s?/, ''))}</blockquote>`);
      i++; continue;
    }
    // List
    if (/^[-*]\s+/.test(line)) {
      if (!inList) { out.push('<ul>'); inList = true; }
      out.push(`<li>${inlineFmt(line.replace(/^[-*]\s+/, ''))}</li>`);
      i++; continue;
    }
    // Paragraph / blank
    if (line.trim() === '') { closeList(); i++; continue; }
    closeList();
    // group consecutive text into paragraph
    let para = [];
    while (i < lines.length && lines[i].trim() !== '' && !/^(#|>|---|[-*]\s|!\[)/.test(lines[i])) {
      para.push(lines[i]); i++;
    }
    out.push(`<p>${inlineFmt(para.join(' ').replace(/\s{2,}$/, '').trim())}</p>`);
  }
  closeList();
  return out.join('\n');
}

function CodeView({ text, lang, onLinkClick }) {
  const highlighted = window.highlightText(text, lang);
  const lines = text.split('\n');
  const bodyRef = useRef(null);

  useEffect(() => {
    const el = bodyRef.current;
    if (!el) return;
    const handler = (e) => {
      const t = e.target;
      if (t.classList && t.classList.contains('tok-link')) {
        const link = t.dataset.link;
        if (link) {
          if (link.startsWith('http') || link.startsWith('mailto')) {
            window.open(link, '_blank');
          } else {
            onLinkClick && onLinkClick(link);
          }
        }
      }
    };
    el.addEventListener('click', handler);
    return () => el.removeEventListener('click', handler);
  }, [text, onLinkClick]);

  return (
    <div className="code-view">
      <div className="gutter">
        {lines.map((_, i) => <span key={i} className="ln">{i + 1}</span>)}
      </div>
      <div
        className="code-body"
        ref={bodyRef}
        dangerouslySetInnerHTML={{ __html: highlighted }}
      />
    </div>
  );
}

function PreviewView({ text }) {
  const html = renderMarkdown(text);
  return <div className="preview-view" dangerouslySetInnerHTML={{ __html: html }} />;
}

function ImageView({ src, alt }) {
  return (
    <div className="image-view">
      <img src={src} alt={alt || ''} />
    </div>
  );
}

function SkillsView() {
  const s = window.PORTFOLIO_DATA.skills;
  const groups = [
    ['Languages', s.languages],
    ['Backend', s.backend],
    ['Frontend', s.frontend],
    ['Databases', s.databases],
    ['Tools & Infrastructure', s.tools],
  ];
  return (
    <div className="skills-view">
      <h1>Skills Dashboard</h1>
      <div className="sub">Tech I've shipped to production — or spent enough time with to know where the footguns are.</div>
      {groups.map(([name, items]) => (
        <div className="skills-group" key={name}>
          <h3>{name} <span className="dash"></span> <span style={{ color: 'var(--text-mute)' }}>{items.length}</span></h3>
          <div className="skill-tags">
            {items.map(t => <span key={t} className="skill-tag">{t}</span>)}
          </div>
        </div>
      ))}
    </div>
  );
}

function WelcomeView({ onOpen }) {
  const D = window.PORTFOLIO_DATA;
  return (
    <div className="welcome">
      <div className="wcol">
        <h1>
          {D.profile.name}
          <span className="small">{D.profile.role} · {D.profile.location}</span>
        </h1>

        <h2>Start</h2>
        <div className="link-row">
          <a className="wlink" onClick={(e) => { e.preventDefault(); onOpen('/README.md'); }} href="#">
            Read the README <span className="muted">— overview of everything</span>
          </a>
          <a className="wlink" onClick={(e) => { e.preventDefault(); onOpen('/experience.md'); }} href="#">
            Browse experience <span className="muted">— 5 roles, 3+ years</span>
          </a>
          <a className="wlink" onClick={(e) => { e.preventDefault(); onOpen('/projects/tetr4dig/README.md'); }} href="#">
            Open a project <span className="muted">— start with TETR4DIG</span>
          </a>
          <a className="wlink" onClick={(e) => { e.preventDefault(); onOpen('/contact.md'); }} href="#">
            Get in touch <span className="muted">— email, GitHub, LinkedIn</span>
          </a>
        </div>

        <h2>Tips</h2>
        <div className="link-row" style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
          <div>Press <span className="kbd">⌘ P</span> to search files</div>
          <div>Press <span className="kbd">⌘ K</span> for the command palette</div>
          <div>Press <span className="kbd">⌘ J</span> to toggle the terminal</div>
          <div>Try <span className="kbd">whoami</span> or <span className="kbd">help</span> in the terminal</div>
        </div>
      </div>

      <div className="wcol">
        <div className="hero-card">
          <span className="tok-com">{`// whoami.ts`}</span>{'\n'}
          <span className="tok-kw">const</span> <span className="tok-var">me</span> <span className="tok-op">=</span> <span className="braces">{`{`}</span>{'\n'}
          {'  '}<span className="key">name</span>: <span className="val">"Leyder Herrera"</span>,{'\n'}
          {'  '}<span className="key">role</span>: <span className="val">"Fullstack Software Engineer"</span>,{'\n'}
          {'  '}<span className="key">age</span>: <span className="tok-num">{D.profile.age}</span>,{'\n'}
          {'  '}<span className="key">location</span>: <span className="val">"Havana, Cuba"</span>,{'\n'}
          {'  '}<span className="key">currently</span>: <span className="val">"AiKoders LLC + CUJAE"</span>,{'\n'}
          {'  '}<span className="key">stack</span>: [<span className="val">"Java"</span>, <span className="val">"Spring"</span>, <span className="val">"Next.js"</span>, <span className="val">"Angular"</span>, <span className="val">"Postgres"</span>],{'\n'}
          {'  '}<span className="key">open_to_work</span>: <span className="tok-bool">true</span>,{'\n'}
          <span className="braces">{`}`}</span>;{'\n\n'}
          <span className="tok-kw">export default</span> <span className="tok-var">me</span>;
        </div>

        <h2 style={{ marginTop: 28 }}>Recent</h2>
        <div className="link-row">
          {D.experience.slice(0, 3).map(e => (
            <a key={e.id} className="wlink" onClick={(ev) => { ev.preventDefault(); onOpen('/experience.md'); }} href="#">
              {e.role} <span className="muted">@ {e.company}</span>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

window.Tabs = Tabs;
window.Breadcrumbs = Breadcrumbs;
window.CodeView = CodeView;
window.PreviewView = PreviewView;
window.ImageView = ImageView;
window.SkillsView = SkillsView;
window.WelcomeView = WelcomeView;
window.resolveFS = resolveFS;
