/* global React,
   FolderIcon, DocIcon, TrashIcon, HardDriveIcon, BrowserIcon,
   ContactsIcon, NotesIcon, AboutIcon, WorkIcon, GearIcon,
   StarIcon, ClockIcon, HouseIcon, FolderTinyIcon, HardDriveTinyIcon,
   GlobeIcon, TagIcon, PersonIcon, DocTinyIcon,
   ChevronLeftIcon, ChevronRightIcon, GridIcon, ListIcon, SearchIcon,
   ShareIcon, PlusIcon,
   WORK, SIDE, POSTS, RATES, ABOUT,
   CASSETTES, IOSPlayerView */

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

/* =========================================================================
   MacWindow — modern macOS chrome (traffic lights, vibrancy, drag, resize)
   ========================================================================= */
function MacWindow({ win, active, onFocus, onClose, onMove, onZoom, onResize, children, toolbar, noBorder }) {
  const startRef = useRef(null);

  function onTitleDown(e) {
    if (e.target.closest('.traffic-light, .tb-btn, button, input')) return;
    onFocus();
    startRef.current = { mx: e.clientX, my: e.clientY, x: win.x, y: win.y };
    function move(ev) {
      const dx = ev.clientX - startRef.current.mx;
      const dy = ev.clientY - startRef.current.my;
      const screenEl = document.getElementById('screen-root');
      const sb = screenEl?.getBoundingClientRect();
      const maxX = sb ? sb.width  - 60 : 9999;
      const maxY = sb ? sb.height - 30 : 9999;
      const nx = Math.max(-win.w + 80, Math.min(maxX, startRef.current.x + dx));
      const ny = Math.max(26, Math.min(maxY, startRef.current.y + dy));
      onMove(nx, ny);
    }
    function up() {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
    }
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
  }

  function onResizeDown(e) {
    e.stopPropagation();
    onFocus();
    const start = { mx: e.clientX, my: e.clientY, w: win.w, h: win.h };
    function move(ev) {
      const nw = Math.max(360, start.w + (ev.clientX - start.mx));
      const nh = Math.max(220, start.h + (ev.clientY - start.my));
      onResize(nw, nh);
    }
    function up() {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
    }
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
  }

  return (
    <div
      className={`window ${active ? 'active' : 'inactive'} opening`}
      style={{ left: win.x, top: win.y, width: win.w, height: win.h, zIndex: win.z }}
      onMouseDown={onFocus}
    >
      <div className={`titlebar ${noBorder ? 'no-border' : ''}`} onMouseDown={onTitleDown} onDoubleClick={onZoom}>
        <div className="traffic-lights">
          <div className="traffic-light red" onClick={(e)=>{e.stopPropagation(); onClose();}} title="Close">
            <span className="glyph">×</span>
          </div>
          <div className="traffic-light yellow" title="Minimize">
            <span className="glyph">−</span>
          </div>
          <div className="traffic-light green" onClick={(e)=>{e.stopPropagation(); onZoom();}} title="Zoom">
            <span className="glyph">⤢</span>
          </div>
        </div>
        {toolbar ? (
          <>
            <div className="titlebar-actions">{toolbar.left}</div>
            <div className="titlebar-title">{win.title}</div>
            <div className="titlebar-spacer"/>
            {toolbar.right}
          </>
        ) : (
          <div className="titlebar-title">{win.title}</div>
        )}
      </div>
      <div className="window-body">{children}</div>
      <div className="grow-box" onMouseDown={onResizeDown} title="Resize"/>
    </div>
  );
}

/* =========================================================================
   Finder shell — sidebar + list. Used for Work, Side, Blogs.
   ========================================================================= */
function FinderShell({ sections, activeId, onPickSection, children }) {
  return (
    <>
      <div className="finder-sidebar scrollable">
        {sections.map((s, i) => (
          <React.Fragment key={i}>
            {s.heading && <div className="sb-section">{s.heading}</div>}
            {s.items.map(it => (
              <div key={it.id}
                   className={`sb-item ${it.id === activeId ? 'active' : ''}`}
                   onClick={() => onPickSection(it.id)}>
                <div className="sb-ico">{it.icon}</div>
                <span>{it.label}</span>
              </div>
            ))}
          </React.Fragment>
        ))}
      </div>
      <div className="finder-main">
        <div className="finder-main-scroll">{children}</div>
      </div>
    </>
  );
}

/* Sidebar config shared across folder windows */
const SIDEBAR_SECTIONS = (active) => ([
  {
    heading: 'Favorites',
    items: [
      { id: 'work',    label: 'Work',          icon: <FolderTinyIcon/> },
      { id: 'side',    label: 'Side Projects', icon: <FolderTinyIcon/> },
      { id: 'blogs',   label: 'Writing',       icon: <DocTinyIcon/> },
      { id: 'about',   label: 'About Me',      icon: <PersonIcon/> },
    ],
  },
  {
    heading: 'Locations',
    items: [
      { id: 'hd', label: 'Macintosh HD', icon: <HardDriveTinyIcon/> },
    ],
  },
  {
    heading: 'Tags',
    items: [
      { id: 't-shipped', label: 'Shipped',  icon: <span style={{display:'inline-block', width:9, height:9, borderRadius:9, background:'#28c840'}}/> },
      { id: 't-essay',   label: 'Essay',    icon: <span style={{display:'inline-block', width:9, height:9, borderRadius:9, background:'#0a84ff'}}/> },
      { id: 't-paid',    label: 'Paid',     icon: <span style={{display:'inline-block', width:9, height:9, borderRadius:9, background:'#febc2e'}}/> },
    ],
  },
]);

function findSectionDefault(id) {
  switch (id) {
    case 'work': return { kind: 'work' };
    case 'side': return { kind: 'side' };
    case 'blogs': return { kind: 'blogs' };
    case 'about': return { kind: 'about-redirect' };
    case 'hd':    return { kind: 'hd' };
    default:      return { kind: 'work' };
  }
}

/* =========================================================================
   Folder views — list view, modern Finder
   ========================================================================= */

function FinderListView({ rows }) {
  const [selected, setSelected] = useState(null);
  return (
    <table className="list-view">
      <thead>
        <tr>{rows.cols.map((c, i) => <th key={i} style={{width: c.w}}>{c.label}</th>)}</tr>
      </thead>
      <tbody>
        {rows.items.map(item => (
          <tr key={item.id}
              className={selected === item.id ? 'selected' : ''}
              onClick={() => setSelected(item.id)}
              onDoubleClick={() => rows.onOpen(item)}>
            {rows.cols.map((c, i) => (
              <td key={i}>
                {i === 0
                  ? <><div className="tiny-icon">{c.icon ? c.icon(item) : <DocIcon size={18}/>}</div>{c.value(item)}</>
                  : c.value(item)}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function WorkFolderView({ openFile }) {
  return (
    <FinderListView rows={{
      cols: [
        { label: 'Name', w: '36%', icon: () => <DocIcon size={18}/>, value: (it) => it.name },
        { label: 'Role', w: '22%', value: (it) => it.role },
        { label: 'When', w: '24%', value: (it) => it.when },
        { label: 'Where', w: '18%', value: (it) => it.where },
      ],
      items: WORK,
      onOpen: openFile,
    }}/>
  );
}

function SideFolderView({ openFile }) {
  return (
    <FinderListView rows={{
      cols: [
        { label: 'Name', w: '46%', icon: () => <DocIcon size={18}/>, value: (it) => it.name },
        { label: 'When', w: '24%', value: (it) => it.when },
        { label: 'Kind', w: '30%', value: () => 'Side project' },
      ],
      items: SIDE,
      onOpen: openFile,
    }}/>
  );
}

function BlogsListView({ openFile }) {
  return (
    <FinderListView rows={{
      cols: [
        { label: 'Title', w: '52%', icon: () => <DocIcon size={18}/>, value: (it) => it.title },
        { label: 'Date',  w: '18%', value: (it) => it.date },
        { label: 'Read',  w: '14%', value: (it) => it.read },
        { label: 'Kind',  w: '16%', value: (it) => it.kind },
      ],
      items: POSTS.map(p => ({...p, name: p.title})),
      onOpen: openFile,
    }}/>
  );
}

/* =========================================================================
   Detail views (article-style)
   ========================================================================= */

function WorkDetail({ item }) {
  return (
    <div className="detail-pane">
      <div className="tag-row">
        <span className="tag accent">{item.role}</span>
        <span className="tag">{item.when}</span>
        <span className="tag">{item.where}</span>
      </div>
      <h1>{item.name}</h1>
      <div className="subhead">{item.summary}</div>
      <div className="meta-row">
        {item.stats.map(s => <span key={s}>{s}</span>)}
      </div>
      <h2>Receipts</h2>
      <ul>{item.bullets.map((b,i) => <li key={i}>{b}</li>)}</ul>
    </div>
  );
}

function SideDetail({ item }) {
  return (
    <div className="detail-pane">
      <div className="tag-row">
        <span className="tag accent">Side project</span>
        <span className="tag">{item.when}</span>
      </div>
      <h1>{item.name}</h1>
      <div className="subhead">{item.summary}</div>
      <h2>Notes</h2>
      <ul>{item.bullets.map((b,i)=><li key={i}>{b}</li>)}</ul>
    </div>
  );
}

function BlogPostView({ item }) {
  return (
    <div className="detail-pane">
      <div className="tag-row">
        <span className="tag accent">{item.kind}</span>
        <span className="tag">{item.date}</span>
        <span className="tag">{item.read}</span>
      </div>
      <h1>{item.title}</h1>
      <div className="subhead">{item.body[0]}</div>
      {item.body.slice(1).map((p,i) => <p key={i}>{p}</p>)}
      <blockquote>Timofey, writing without permission, as usual.</blockquote>
    </div>
  );
}

/* =========================================================================
   Browser (Safari-ish), Address Book, About, Control Panel
   ========================================================================= */

function BrowserResume() {
  return (
    <div style={{display:'flex', flexDirection:'column', flex:1, width:'100%', minWidth:0, height:'100%'}}>
      <div className="browser-toolbar">
        <div className="tb-btn"><ChevronLeftIcon/></div>
        <div className="tb-btn disabled"><ChevronRightIcon/></div>
        <div className="browser-pill">
          <SearchIcon size={12}/>
          <span>portfolio.timofeymakhlay.com/resume</span>
        </div>
        <div className="tb-btn"><ShareIcon/></div>
      </div>
      <div style={{flex:1, overflow:'auto'}} className="finder-main-scroll">
        <div className="detail-pane" style={{maxWidth: 720}}>
          <h1 style={{fontSize:32}}>Timofey Makhlay</h1>
          <div className="subhead" style={{fontSize:15}}>
            Founding / full-stack engineer · Berlin · San Francisco
          </div>
          <div className="meta-row">
            <span>tmakhlay2@gmail.com</span>
            <span className="dot"/>
            <span>linkedin.com/in/timofeymakhlay</span>
            <span className="dot"/>
            <span>EN · RU · IT</span>
          </div>
          <p>10+ years building product at the seam between infra, web, and mobile. Founding-engineer DNA. Trades architecture for velocity on purpose, then pays the debt down before it compounds.</p>

          <h2>Selected experience</h2>
          {WORK.map(w => (
            <div key={w.id} style={{marginBottom: 18}}>
              <h3 style={{marginBottom: 2}}>
                {w.name} <span style={{fontWeight:500, color:'var(--mac-text-3)'}}>— {w.role}</span>
              </h3>
              <div style={{fontSize:12, color:'var(--mac-text-3)', marginBottom: 6}}>
                {w.when} · {w.where}
              </div>
              <p style={{marginBottom:6}}>{w.summary}</p>
              <ul style={{marginBottom:6}}>{w.bullets.slice(0,2).map((b,i) => <li key={i}>{b}</li>)}</ul>
              <div className="tag-row">{w.stats.map(s => <span key={s} className="tag">{s}</span>)}</div>
            </div>
          ))}

          <h2>Selected side projects</h2>
          <ul>
            {SIDE.map(s => <li key={s.id}><strong>{s.name}</strong> <span style={{color:'var(--mac-text-3)'}}>· {s.when}</span> — {s.summary.split('.')[0]}.</li>)}
          </ul>

          <h2>Writing</h2>
          <ul>{POSTS.map(p => <li key={p.id}>{p.title} <span style={{color:'var(--mac-text-3)'}}>· {p.date}</span></li>)}</ul>

          <h2>Education</h2>
          <ul>
            <li>Make School — B.A.S. Computer Science (2017 — 2020)</li>
            <li>Y Combinator Startup School (2020)</li>
          </ul>

          <h2>Honors</h2>
          <ul><li>Make School — Best iOS Game, Summer 2017</li></ul>
        </div>
      </div>
    </div>
  );
}

function AddressBookApp() {
  return (
    <div style={{display:'flex', height:'100%'}}>
      <div className="finder-sidebar scrollable" style={{width: 180}}>
        <div className="sb-section">Groups</div>
        <div className="sb-item active"><div className="sb-ico"><PersonIcon/></div><span>All Contacts</span></div>
        <div className="sb-item"><div className="sb-ico"><StarIcon/></div><span>VIP</span></div>
        <div className="sb-item"><div className="sb-ico"><FolderTinyIcon/></div><span>Clients</span></div>
        <div className="sb-item"><div className="sb-ico"><FolderTinyIcon/></div><span>Founders</span></div>
      </div>
      <div className="finder-main">
        <div className="finder-main-scroll">
          <div className="detail-pane">
            <div className="contact-hero">
              <div className="contact-avatar">TM</div>
              <div>
                <h1 style={{fontSize:24, marginBottom:2}}>Timofey Makhlay</h1>
                <div className="subhead" style={{marginBottom:6}}>Founding / full-stack engineer</div>
                <div style={{display:'flex', gap:8}}>
                  <button className="mac-btn primary">Message</button>
                  <button className="mac-btn">Email</button>
                </div>
              </div>
            </div>

            <div className="kv-list" style={{marginTop:14}}>
              <div className="kv-row"><span className="k">email</span><span className="v">tmakhlay2@gmail.com</span></div>
              <div className="kv-row"><span className="k">linkedin</span><span className="v">linkedin.com/in/timofeymakhlay</span></div>
              <div className="kv-row"><span className="k">based in</span><span className="v">Berlin / San Francisco</span></div>
              <div className="kv-row"><span className="k">languages</span><span className="v">English · Russian · Italian</span></div>
              <div className="kv-row"><span className="k">availability</span><span className="v">Booking Q3 2026 — one slot left</span></div>
              <div className="kv-row"><span className="k">note</span><span className="v">Reply with the shape of the problem and I'll tell you whether I'm the right person for it.</span></div>
            </div>

            <h2>Rates</h2>
            {RATES.map(r => (
              <div className="rate-card" key={r.who}>
                <div>
                  <div className="who">{r.who}</div>
                  <div className="desc">{r.desc}</div>
                </div>
                <div>
                  <div className="price">{r.price}</div>
                  <div className="unit">{r.unit}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function AboutApp() {
  return (
    <div className="detail-pane">
      <div className="contact-hero">
        <div className="contact-avatar">TM</div>
        <div>
          <h1 style={{marginBottom:2}}>{ABOUT.hello}</h1>
          <div className="subhead">10+ years · iOS, web, infra, the seam between</div>
        </div>
      </div>
      <div className="tag-row">{ABOUT.facts.map(f => <span key={f} className="tag">{f}</span>)}</div>
      {ABOUT.blurb.map((p,i) => <p key={i}>{p}</p>)}
      <h2>What I'm good for</h2>
      <ul>
        <li>0 → 1 product engineering, especially when the right answer hasn't been found yet.</li>
        <li>Infra you can actually maintain — Postgres before Kafka, until Kafka.</li>
        <li>Frontend systems that survive their second engineer.</li>
        <li>Telling you the boring truth instead of the exciting lie.</li>
      </ul>
      <h2>What I'm not</h2>
      <ul>
        <li>Cheap. (Honest, though.)</li>
        <li>An ML researcher. I ship the product around the model.</li>
        <li>A consultant in the bad sense.</li>
      </ul>
    </div>
  );
}

function ControlPanel({ tweaks, setTweak }) {
  return (
    <div style={{display:'flex', height:'100%'}}>
      <div className="finder-sidebar scrollable" style={{width: 180}}>
        <div className="sb-section">Settings</div>
        <div className="sb-item active"><div className="sb-ico"><GlobeIcon/></div><span>Appearance</span></div>
        <div className="sb-item"><div className="sb-ico"><HouseIcon/></div><span>Desktop</span></div>
        <div className="sb-item"><div className="sb-ico"><ClockIcon/></div><span>Date & Time</span></div>
        <div className="sb-item"><div className="sb-ico"><PersonIcon/></div><span>About</span></div>
      </div>
      <div className="finder-main">
        <div className="finder-main-scroll">
          <div className="detail-pane">
            <h1 style={{fontSize:22}}>Appearance</h1>
            <div className="subhead">Same controls as Tweaks, in a window, for completeness.</div>

            <h2>Theme</h2>
            <div style={{display:'flex', gap:10, marginBottom:8}}>
              <button className={`mac-btn ${!tweaks.darkMode ? 'primary' : ''}`} onClick={()=>setTweak('darkMode', false)}>Light</button>
              <button className={`mac-btn ${tweaks.darkMode ? 'primary' : ''}`} onClick={()=>setTweak('darkMode', true)}>Dark</button>
            </div>

            <h2>Accent color</h2>
            <div style={{display:'flex', gap:10, marginBottom:8}}>
              {[
                {v:'#0a84ff', n:'Blue'},
                {v:'#bf5af2', n:'Purple'},
                {v:'#ff375f', n:'Pink'},
                {v:'#ff9f0a', n:'Orange'},
                {v:'#30d158', n:'Green'},
                {v:'#5e5ce6', n:'Indigo'},
              ].map(c => (
                <button key={c.v} title={c.n}
                        onClick={()=>setTweak('accent', c.v)}
                        style={{
                          width: 26, height: 26, borderRadius: 999,
                          border: tweaks.accent === c.v ? '2px solid var(--mac-text)' : '0.5px solid var(--mac-stroke-strong)',
                          background: c.v, cursor: 'default',
                          padding: 0,
                        }}/>
              ))}
            </div>

            <h2>Intro</h2>
            <button className={`mac-btn ${tweaks.skipIntro ? 'primary' : ''}`} onClick={()=>setTweak('skipIntro', !tweaks.skipIntro)}>
              {tweaks.skipIntro ? 'Intro is skipped' : 'Skip the zoom intro'}
            </button>

            <h2>Build</h2>
            <ul>
              <li>v4.3 · last deploy 2026-04-26 09:14 CEST</li>
              <li>macOS Makhlay (Sequoia-spirited). Original chrome. Vintage chassis.</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}

/* =========================================================================
   Music — Mac variant. Sidebar library + the iOS player view dropped into
   the right pane. The player is rich enough on its own that giving it a
   wider window is the only Mac-specific work; the tiny library list mirrors
   the iOS rows so the same album art / now-playing indicator reads on both.
   ========================================================================= */
function MusicApp({ audioApi }) {
  const [selectedId, setSelectedId] = useState(
    () => audioApi.active?.id || CASSETTES[0].id
  );
  const selected = CASSETTES.find(c => c.id === selectedId) || CASSETTES[0];

  // Same gesture model as iOS: showing a cassette in the player loads it.
  useEffect(() => {
    if (!selected) return;
    if (!audioApi.active || audioApi.active.id !== selected.id) {
      audioApi.pick(selected);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedId]);

  return (
    <div className="music-mac">
      <div className="music-mac-sidebar scrollable">
        <div className="sb-section">Library</div>
        <div className="music-mac-rows">
          {CASSETTES.map(c => {
            const isActive = audioApi.active && audioApi.active.id === c.id;
            const isPlaying = isActive && !audioApi.paused;
            const artStyle = c.cover
              ? { backgroundImage: `url("${c.cover}")` }
              : { background: c.color };
            return (
              <div key={c.id}
                   className={`music-track ${selectedId === c.id ? 'selected' : ''}`}
                   onClick={() => setSelectedId(c.id)}>
                <div className="music-track-art" style={artStyle}/>
                <div className="music-track-text">
                  <div className="music-track-title">{c.title}</div>
                  <div className="music-track-artist">{c.artist}</div>
                </div>
                {isActive ? (
                  <span className={`ios-music-bars ${isPlaying ? 'on' : ''}`}>
                    <i/><i/><i/>
                  </span>
                ) : (
                  <span className="music-track-dur">{c.duration}</span>
                )}
              </div>
            );
          })}
        </div>
      </div>
      <div className="music-mac-player">
        <IOSPlayerView cassette={selected} audioApi={audioApi}/>
      </div>
    </div>
  );
}

Object.assign(window, {
  MacWindow,
  FinderShell, SIDEBAR_SECTIONS, findSectionDefault,
  WorkFolderView, WorkDetail,
  SideFolderView, SideDetail,
  BlogsListView, BlogPostView,
  BrowserResume, AddressBookApp, AboutApp, ControlPanel,
  MusicApp,
});
