// Your Argentine Developer — main app
const { useState, useEffect, useCallback, useRef } = React;

// ============ Tweaks ============
function useTweaksLocal(defaults) {
  const [t, setT] = useState(defaults);
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data && e.data.type === '__edit_mode_set_keys' && e.data.edits) {
        setT((prev) => ({ ...prev, ...e.data.edits }));
      }
    };
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
  }, []);
  const setTweak = useCallback((k, v) => {
    setT((prev) => {
      const next = typeof k === 'object' ? { ...prev, ...k } : { ...prev, [k]: v };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: typeof k === 'object' ? k : { [k]: v } }, '*');
      return next;
    });
  }, []);
  return [t, setTweak];
}

// ============ Routing ============
const PAGES = {
  home: { id: 'home', urlEs: '/', urlEn: '/', titleEs: 'Inicio', titleEn: 'Home' },
  about: { id: 'about', urlEs: '/acerca', urlEn: '/about', titleEs: 'Acerca del Dev', titleEn: 'About' },
  services: { id: 'services', urlEs: '/servicios', urlEn: '/services', titleEs: 'Servicios', titleEn: 'Services' },
  contact: { id: 'contact', urlEs: '/contacto', urlEn: '/contact', titleEs: 'Contacto', titleEn: 'Contact' },
  notFound: { id: 'notFound', urlEs: '/404', urlEn: '/404', titleEs: '404 — Not Found', titleEn: '404 — Not Found' },
};

function isProductId(id) { return !!PRODUCT_DETAILS[id]; }

// ============ Browser Chrome ============
function BrowserChrome({ history, idx, onBack, onForward, onHome, onMail, onSubmitUrl, lang, currentLabel, loading }) {
  const url = `www.michelsohn.dev${getUrlSuffix(history[idx], lang)}`;
  const [edit, setEdit] = useState(url);
  useEffect(() => setEdit(url), [url]);

  return (
    <div className="browser">
      <div className="browser-titlebar">
        <span style={{ display: 'inline-block', width: 16, height: 16, background: 'linear-gradient(135deg,#74acdf 50%,#fff 50%)', border: '1px solid #000', marginRight: 4 }}></span>
        <span className="title-text">Your Argentine Developer — Mozaic Browser 4.0 [{currentLabel}]</span>
        <button className="titlebar-btn" title="Minimize">_</button>
        <button className="titlebar-btn" title="Maximize">▢</button>
        <button className="titlebar-btn" title="Close" style={{ background: '#d24545', color: '#fff' }}>×</button>
      </div>
      <div className="browser-toolbar">
        <div className="nav-arrows">
          <button onClick={onBack} disabled={idx <= 0} title="Atrás">◀</button>
          <button onClick={onForward} disabled={idx >= history.length - 1} title="Adelante">▶</button>
        </div>
        <form
          style={{ flex: 1, display: 'flex' }}
          onSubmit={(e) => { e.preventDefault(); onSubmitUrl(edit); }}
        >
          <input
            className="url-bar"
            value={edit}
            onChange={(e) => setEdit(e.target.value)}
            spellCheck={false}
          />
        </form>
        <button className="toolbar-btn" title="Email" onClick={onMail}>✉</button>
        <button className="toolbar-btn" title="Inicio" onClick={onHome}>⌂</button>
      </div>
    </div>
  );
}

function getUrlSuffix(pageId, lang) {
  if (PAGES[pageId]) return lang === 'es' ? PAGES[pageId].urlEs : PAGES[pageId].urlEn;
  if (isProductId(pageId)) return `/${lang === 'es' ? 'producto' : 'product'}/${pageId}`;
  return '/';
}

// ============ Sidebar ============
function Sidebar({ active, onNav, lang }) {
  return (
    <nav className="sidebar">
      <ul className="nav-list">
        {NAV_ITEMS.map((item) => (
          <li key={item.id}>
            <button
              className={active === item.id ? 'active' : ''}
              onClick={() => onNav(item.id)}
            >
              {item[lang]}
            </button>
          </li>
        ))}
      </ul>
      <div style={{ padding: '16px 12px', fontFamily: 'VT323, monospace', color: 'var(--banner-deepest)', fontSize: 20, lineHeight: 1.2, textAlign: 'center', fontWeight: 'bold' }}>
        <span style={{ color: 'var(--yellow)', textShadow: '1px 1px 0 var(--green-darker)', fontSize: 22 }}>★</span> 4,98 / 5
      </div>
    </nav>
  );
}

// ============ Home Page ============
function HomePage({ tweaks, onNav, lang, onPortraitClick }) {
  const copy = HOME_COPY[lang];
  return (
    <div>
      <div className="logo-row">
        <div className="logo-symbol">
          <div className="logo-glyph">{'</>'}</div>
        </div>
        <div className="logo-text">
          <h1>
            YOUR<br/>
            ARGENTINE<br/>
            DEVELOPER
          </h1>
        </div>
      </div>

      <div className="tagline">
        {copy.tagline1}<br/>
        {copy.tagline2}
      </div>

      {tweaks.showMarquee && (
        <div className="marquee-strip">
          <div className="track">
            <span>{MARQUEE_LINES[lang]}</span>
            <span>{MARQUEE_LINES[lang]}</span>
            <span>{MARQUEE_LINES[lang]}</span>
            <span>{MARQUEE_LINES[lang]}</span>
          </div>
        </div>
      )}

      <div className="layout">
        <Sidebar active="home" onNav={onNav} lang={lang} />
        <main className="main">
          <div style={{ height: 14 }}></div>

          <div className="portrait-row">
            <div className="portrait" style={{ padding: 0, cursor: 'pointer' }} onClick={onPortraitClick} title="Click me">
              <img
                src={window.PORTRAIT_DATA_URI || "assets/francisco-portrait.png"}
                alt="Francisco Michelsohn"
                draggable="false"
                style={{
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                  objectPosition: 'center 20%',
                  display: 'block',
                  background: '#1c4dba',
                  pointerEvents: 'none',
                }}
              />
            </div>
            <div className="quote-block">
              <h3 className="quote-name">{copy.devName}</h3>
              <div className="quote-text">
                {copy.quote.map((p, i) => <p key={i}>{p}</p>)}
              </div>
            </div>
          </div>

          <div className="promo-row">
            {tweaks.showStarburst && (
              <div className="starburst-wrap">
                <div className="starburst">
                  <div className="label-top">{copy.discountTop}</div>
                  <div className="big">{tweaks.discount}{copy.discountBig}</div>
                  <div className="small">
                    {copy.discountMid}
                    {copy.discountBottom.split('\n').map((line, i) => (
                      <React.Fragment key={i}><br/>{line}</React.Fragment>
                    ))}
                  </div>
                </div>
              </div>
            )}
            <div className="welcome" style={{ gridColumn: tweaks.showStarburst ? 'auto' : '1 / -1' }}>
              <h2>{copy.welcomeTitle}</h2>
              <p>{copy.welcomeText}</p>
              {copy.welcomeExtra && <p style={{ marginTop: 10 }}>{copy.welcomeExtra}</p>}
              {copy.welcomeExtra2 && <p style={{ marginTop: 10 }}>{copy.welcomeExtra2}</p>}
            </div>
          </div>

          <div className="body-copy">
            {copy.body.map((p, i) => {
              const last = i === copy.body.length - 1;
              return last
                ? <p key={i}>{p}</p>
                : i === 1
                  ? <p key={i} className="lead">{p}</p>
                  : <p key={i}>{p.split('www.michelsohn.dev').map((seg, j, arr) => (
                      <React.Fragment key={j}>
                        {seg}{j < arr.length - 1 && <a href="https://michelsohn.dev" target="_blank" rel="noreferrer">www.michelsohn.dev</a>}
                      </React.Fragment>
                    ))}</p>;
            })}

            <div className="product-grid">
              {NAV_ITEMS.filter(n => n.id !== 'home').map((item) => (
                <a key={item.id} href="#" onClick={(e) => { e.preventDefault(); onNav(item.id); }}>{item[lang]}</a>
              ))}
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}

// ============ Product Detail Page ============
function ProductPage({ id, onNav, lang, tweaks }) {
  const detail = PRODUCT_DETAILS[id][lang];
  return (
    <div>
      <div className="logo-row" style={{ minHeight: 90 }}>
        <div className="logo-symbol" style={{ padding: '6px 6px' }}>
          <div className="logo-glyph" style={{ fontSize: 56 }}>{'</>'}</div>
        </div>
        <div className="logo-text" style={{ padding: '10px 16px' }}>
          <h1 style={{ fontSize: 36 }}>YOUR ARGENTINE DEVELOPER</h1>
        </div>
      </div>
      <div className="layout">
        <Sidebar active={id} onNav={onNav} lang={lang} />
        <main className="main">
          <h2 className="inner-title">{detail.title}</h2>
          <div className="inner-block">
            <p style={{ fontSize: 15 }}>{detail.desc}</p>
            {(() => {
              const links = PRODUCT_DETAILS[id].links || {};
              if (links.demo) {
                return <a className="price" href={links.demo} target="_blank" rel="noreferrer" style={{ textDecoration: 'none', cursor: 'pointer' }}>{lang === 'es' ? '🌐 Demo pública ↗' : '🌐 Public demo ↗'}</a>;
              }
              if (links.repo) {
                return <a className="price" href={links.repo} target="_blank" rel="noreferrer" style={{ textDecoration: 'none', cursor: 'pointer' }}>{lang === 'es' ? '⌨ Ver código en GitHub ↗' : '⌨ See code on GitHub ↗'}</a>;
              }
              if (links.doc) {
                return <a className="price" href={links.doc} target="_blank" rel="noreferrer" style={{ textDecoration: 'none', cursor: 'pointer' }}>{lang === 'es' ? '📄 Sobre el proyecto ↗' : '📄 About the project ↗'}</a>;
              }
              return <div className="price">{detail.price}</div>;
            })()}
          </div>

          <div className="inner-block" style={{ background: 'var(--mint)' }}>
            <h3>{lang === 'es' ? '¿Cómo trabajar conmigo?' : 'How do we work together?'}</h3>
            <p>{lang === 'es' ? '1. Mandás un mail por la sección Contacto explicando tu situación.' : '1. Send an email through the Contact page explaining your situation.'}</p>
            <p>{lang === 'es' ? '2. Te contesto en menos de 24 horas hábiles GMT-3 (post-mate).' : '2. I reply within 24 business hours GMT-3 (post-mate).'}</p>
            <p>{lang === 'es' ? '3. Firmamos un contrato razonable y sin abogados.' : '3. We sign a reasonable contract, no lawyers needed.'}</p>
            <p>{lang === 'es' ? '4. Empezamos el lunes. O el martes. Pero antes del jueves.' : '4. We start Monday. Or Tuesday. But before Thursday.'}</p>
          </div>
        </main>
      </div>
    </div>
  );
}

// ============ About Page ============
function AboutPage({ onNav, lang }) {
  const copy = ABOUT_COPY[lang];
  return (
    <div>
      <div className="logo-row" style={{ minHeight: 90 }}>
        <div className="logo-symbol" style={{ padding: '6px 6px' }}>
          <div className="logo-glyph" style={{ fontSize: 56 }}>{'</>'}</div>
        </div>
        <div className="logo-text" style={{ padding: '10px 16px' }}>
          <h1 style={{ fontSize: 36 }}>YOUR ARGENTINE DEVELOPER</h1>
        </div>
      </div>
      <div className="layout">
        <Sidebar active="about" onNav={onNav} lang={lang} />
        <main className="main">
          <h2 className="inner-title">{copy.title}</h2>
          {copy.bio.map(([h, p], i) => (
            <div key={i} className="inner-block">
              <h3>{h}</h3>
              <p>{p}</p>
            </div>
          ))}
        </main>
      </div>
    </div>
  );
}

const FORMSPREE_ENDPOINT = 'https://formspree.io/f/xbjenpkd';

// ============ Contact Page ============
function ContactPage({ onNav, lang }) {
  const copy = CONTACT_COPY[lang];
  const ui = UI_LABELS[lang];
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    const formData = new FormData(e.target);
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        body: formData,
        headers: { Accept: 'application/json' },
      });
      if (res.ok) {
        setSent(true);
        e.target.reset();
      } else {
        const data = await res.json().catch(() => ({}));
        setError((data.errors && data.errors[0] && data.errors[0].message)
          || (lang === 'es' ? 'No pudimos enviar el mensaje. Probá de nuevo.' : 'We could not send the message. Try again.'));
      }
    } catch (err) {
      setError(lang === 'es' ? 'Error de red. Revisá tu conexión.' : 'Network error. Check your connection.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div>
      <div className="logo-row" style={{ minHeight: 90 }}>
        <div className="logo-symbol" style={{ padding: '6px 6px' }}>
          <div className="logo-glyph" style={{ fontSize: 56 }}>{'</>'}</div>
        </div>
        <div className="logo-text" style={{ padding: '10px 16px' }}>
          <h1 style={{ fontSize: 36 }}>YOUR ARGENTINE DEVELOPER</h1>
        </div>
      </div>
      <div className="layout">
        <Sidebar active="contact" onNav={onNav} lang={lang} />
        <main className="main">
          <h2 className="inner-title">{copy.title}</h2>
          {sent ? (
            <div className="inner-block" style={{ background: 'var(--mint)' }}>
              <h3>{ui.sentTitle}</h3>
              <p>{ui.sentBody}</p>
              <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
                <button className="submit-btn" onClick={() => setSent(false)}>{ui.sentAgain}</button>
                <button className="submit-btn" style={{ background: 'linear-gradient(180deg,#888,#666)', borderColor: '#444' }} onClick={() => onNav('home')}>◀ {ui.backHome}</button>
              </div>
            </div>
          ) : (
            <form className="contact-form" onSubmit={handleSubmit}>
              <p style={{ margin: 0, fontSize: 14 }}>{copy.intro}</p>
              <input type="hidden" name="_subject" value={lang === 'es' ? 'Consulta desde Your Argentine Developer' : 'Inquiry from Your Argentine Developer'} />
              <input type="hidden" name="_language" value={lang} />
              <label>{copy.fields.name}</label>
              <input type="text" name="name" required defaultValue="" />
              <label>{copy.fields.email}</label>
              <input type="email" name="email" required defaultValue="" placeholder="vos@empresa.com" />
              <label>{copy.fields.company}</label>
              <input type="text" name="company" defaultValue="" />
              <label>{copy.fields.budget}</label>
              <select name="budget" defaultValue={copy.budgetOptions[1]}>
                {copy.budgetOptions.map(opt => <option key={opt}>{opt}</option>)}
              </select>
              <label>{copy.fields.message}</label>
              <textarea name="message" required placeholder={lang === 'es' ? 'Contame qué necesitás...' : 'Tell me what you need...'} />
              {error && (
                <p style={{ marginTop: 10, color: '#c41020', fontWeight: 'bold', fontSize: 13 }}>
                  ⚠ {error}
                </p>
              )}
              <div style={{ marginTop: 12 }}>
                <button type="submit" className="submit-btn" disabled={submitting}>
                  {submitting
                    ? (lang === 'es' ? 'ENVIANDO...' : 'SENDING...')
                    : copy.submit}
                </button>
              </div>
              <p style={{ marginTop: 14, fontSize: 13 }}>
                {copy.or} <a href={`mailto:${CONTACT_LINKS.email}`} style={{ color: 'var(--link)' }}>{CONTACT_LINKS.email}</a>
              </p>
              <p style={{ marginTop: 6, fontSize: 13 }}>
                <a href={CONTACT_LINKS.linkedin} target="_blank" rel="noreferrer" style={{ color: 'var(--link)' }}>LinkedIn ↗</a>
                {' · '}
                <a href={CONTACT_LINKS.github} target="_blank" rel="noreferrer" style={{ color: 'var(--link)' }}>GitHub ↗</a>
              </p>
            </form>
          )}
        </main>
      </div>
    </div>
  );
}

// ============ Services list (shown if user types /servicios) ============
function ServicesPage({ onNav, lang }) {
  return (
    <div>
      <div className="logo-row" style={{ minHeight: 90 }}>
        <div className="logo-symbol" style={{ padding: '6px 6px' }}>
          <div className="logo-glyph" style={{ fontSize: 56 }}>{'</>'}</div>
        </div>
        <div className="logo-text" style={{ padding: '10px 16px' }}>
          <h1 style={{ fontSize: 36 }}>YOUR ARGENTINE DEVELOPER</h1>
        </div>
      </div>
      <div className="layout">
        <Sidebar active="services" onNav={onNav} lang={lang} />
        <main className="main">
          <h2 className="inner-title">{lang === 'es' ? 'TODOS LOS SERVICIOS' : 'ALL SERVICES'}</h2>
          {Object.entries(PRODUCT_DETAILS).map(([id, all]) => {
            const d = all[lang];
            return (
              <div key={id} className="inner-block">
                <h3><a href="#" onClick={(e) => { e.preventDefault(); onNav(id); }}>{d.title}</a></h3>
                <p>{d.desc}</p>
                <div className="price">{d.price}</div>
              </div>
            );
          })}
        </main>
      </div>
    </div>
  );
}

// ============ Footer ============
function Footer({ lang, visits, onCounterClick }) {
  const t = UI_LABELS[lang];
  return (
    <footer className="site-footer">
      <div>
        © 2026 Francisco Michelsohn — Your Argentine Developer. {lang === 'es' ? 'Todos los derechos al revés.' : 'All rights reversed.'}
        <span className="flag" title="Argentina"></span>
        {lang === 'es' ? 'Hecho en Buenos Aires con muchas ganas y poca dormida.' : 'Made in Buenos Aires with lots of caffeine and little sleep.'}
      </div>
      <div>
        <span style={{ marginRight: 10 }}>{t.visitors}</span>
        <span
          className="counter"
          onClick={onCounterClick}
          style={{ cursor: 'pointer' }}
          title="Click me"
        >{String(visits).padStart(7, '0')}</span>
      </div>
    </footer>
  );
}

// ============ Status Bar ============
function StatusBar({ lang, loading, currentLabel }) {
  const t = UI_LABELS[lang];
  return (
    <div className="statusbar">
      <span>
        {loading ? <><span className="spinner" style={{ display: 'inline-block', width: 12, height: 12, verticalAlign: 'middle', marginRight: 6, borderWidth: 2 }}></span>{t.pageLoading}...</> : <>● {t.statusReady}</>}
      </span>
      <span>{currentLabel}</span>
      <span><span className="lock">🔒</span> {t.secure} — SSL 3.0</span>
    </div>
  );
}

// ============ NotFound Page ============
function NotFoundPage({ onNav, lang }) {
  return (
    <div>
      <div className="logo-row" style={{ minHeight: 90 }}>
        <div className="logo-symbol" style={{ padding: '6px 6px' }}>
          <div className="logo-glyph" style={{ fontSize: 56 }}>{'</>'}</div>
        </div>
        <div className="logo-text" style={{ padding: '10px 16px' }}>
          <h1 style={{ fontSize: 36 }}>YOUR ARGENTINE DEVELOPER</h1>
        </div>
      </div>
      <div className="layout">
        <Sidebar active="notFound" onNav={onNav} lang={lang} />
        <main className="main" style={{ textAlign: 'center', padding: '60px 30px 80px' }}>
          <div style={{
            fontFamily: '"Anton","Arial Black",sans-serif',
            fontSize: 220,
            lineHeight: 0.85,
            color: 'var(--banner-red-dark)',
            letterSpacing: '-0.02em',
            textShadow: '6px 6px 0 var(--banner-deepest)',
            margin: '20px 0 10px',
          }}>404</div>
          <h2 style={{
            fontFamily: '"Press Start 2P","Anton",sans-serif',
            fontSize: 28,
            color: '#111',
            textTransform: 'uppercase',
            letterSpacing: '0.04em',
            margin: '10px 0 26px',
            lineHeight: 1.2,
          }}>{lang === 'es' ? 'PÁGINA NO ENCONTRADA' : 'PAGE NOT FOUND'}</h2>
          <p style={{
            fontFamily: 'Verdana,sans-serif',
            fontSize: 18,
            color: '#333',
            maxWidth: 520,
            margin: '0 auto 24px',
            lineHeight: 1.5,
            fontStyle: 'italic',
          }}>
            {lang === 'es'
              ? '"La página que pediste probablemente está dando vueltas con Roman en la parada de taxis."'
              : '"The page you requested is probably hanging out with Roman at the cab depot."'}
          </p>
          <p style={{
            fontFamily: '"VT323","Courier New",monospace',
            fontSize: 16,
            color: '#666',
            marginBottom: 28,
          }}>{lang === 'es' ? 'Error 404 · Ruta inexistente' : 'Error 404 · Route not found'}</p>
          <a href="#" onClick={(e) => { e.preventDefault(); onNav('home'); }}
             className="submit-btn" style={{ textDecoration: 'none', display: 'inline-block' }}>
            ◀ {lang === 'es' ? 'VOLVER AL INICIO' : 'BACK TO HOME'}
          </a>
        </main>
      </div>
    </div>
  );
}

// ============ GTA-style Popup ============
function Popup({ title, body, button, onClose, color }) {
  if (!title) return null;
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 9999, padding: 20,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--chrome)',
          border: '2px solid #000',
          boxShadow: 'inset 0 1px 0 #fff, inset 0 0 0 3px var(--chrome-dark), 0 10px 40px rgba(0,0,0,0.7)',
          minWidth: 380, maxWidth: 480,
          fontFamily: 'Verdana,sans-serif',
        }}
      >
        <div style={{
          background: `linear-gradient(180deg, ${color || '#4a6cbf'} 0%, ${color ? color : '#1c3d80'} 100%)`,
          color: '#fff',
          fontFamily: '"Trebuchet MS",Verdana,sans-serif',
          fontSize: 13,
          fontWeight: 'bold',
          padding: '6px 10px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          borderBottom: '1px solid #000',
          textShadow: '1px 1px 0 rgba(0,0,0,0.4)',
        }}>
          <span>{title}</span>
          <button onClick={onClose} style={{
            background: 'var(--chrome)', border: '1px solid #000',
            boxShadow: 'inset 1px 1px 0 #fff, inset -1px -1px 0 var(--chrome-dark)',
            width: 18, height: 16, color: '#000',
            fontFamily: 'Arial Black,sans-serif', fontSize: 10, fontWeight: 'bold',
            cursor: 'pointer', lineHeight: 1,
          }}>×</button>
        </div>
        <div style={{ padding: '22px 20px 18px', textAlign: 'center' }}>
          <div style={{
            fontFamily: '"Press Start 2P","Anton",sans-serif',
            fontSize: 22,
            color: color || 'var(--banner-deepest)',
            textTransform: 'uppercase',
            lineHeight: 1.2,
            marginBottom: 14,
            letterSpacing: '0.02em',
          }}>{body.headline}</div>
          {body.text && (
            <div style={{
              fontFamily: 'Verdana,sans-serif',
              fontSize: 14, color: '#333', lineHeight: 1.5,
              marginBottom: 16,
            }}>{body.text}</div>
          )}
          <button onClick={onClose} className="submit-btn" style={{ marginTop: 4 }}>
            {button}
          </button>
        </div>
      </div>
    </div>
  );
}

const CHEAT_POPUPS = {
  gtaiv: {
    title: '★ CHEAT ACTIVATED ★',
    color: '#97091c',
    body: {
      headline: 'GTA IV MODE',
      text: 'Niko Bellic ha tomado control de este portfolio. Aguanten los rusos del Liberty City.',
    },
  },
  bowling: {
    title: '★ CHEAT ACTIVATED ★',
    color: '#00713a',
    body: {
      headline: '"WANNA GO BOWLING?"',
      text: 'Roman te quiere llevar al bowling. Ignoralo y volvé al portfolio.',
    },
  },
  mozaic: {
    title: '★ HIDDEN PAGE ★',
    color: '#1c3d80',
    body: {
      headline: 'MOZAIC BROWSER 4.0',
      text: 'El navegador retro que estás usando ahora mismo. Hecho a mano, sin trackers ni cookies. Promesa de honor.',
    },
  },
  cousin: {
    title: '★ COUSIN! ★',
    color: '#97091c',
    body: {
      headline: 'HEY COUSIN!',
      text: '"Let\'s go bowling!" — Roman Bellic',
    },
  },
  hey_cousin: {
    title: '★ INCOMING CALL ★',
    color: '#97091c',
    body: {
      headline: 'HEY COUSIN!',
      text: '"LET\'S GO DEPLOY SOME CODE!"',
    },
  },
  counter: {
    title: '★ VISITOR COUNTER ★',
    color: '#003a1c',
    body: {
      headline: 'WOW.',
      text: 'Alguien realmente clickeó esto. El visitante #42.771.039 no recibe absolutamente nada.',
    },
  },
};

// ============ App ============
function App() {
  const defaults = window.__TWEAK_DEFAULTS;
  const [tweaks, setTweak] = useTweaksLocal(defaults);
  const [history, setHistory] = useState(['home']);
  const [idx, setIdx] = useState(0);
  const [loading, setLoading] = useState(false);
  const [loadingTarget, setLoadingTarget] = useState(null);
  const [popup, setPopup] = useState(null);
  const [portraitClicks, setPortraitClicks] = useState(0);
  const portraitTimerRef = useRef(null);
  const visits = 42_771_038;

  const onPortraitClick = () => {
    setPortraitClicks((c) => {
      const next = c + 1;
      if (next >= 5) {
        setPopup(CHEAT_POPUPS.hey_cousin);
        return 0;
      }
      // Reset count after 2s of inactivity
      if (portraitTimerRef.current) clearTimeout(portraitTimerRef.current);
      portraitTimerRef.current = setTimeout(() => setPortraitClicks(0), 2000);
      return next;
    });
  };

  const onCounterClick = () => setPopup(CHEAT_POPUPS.counter);

  // Listen for cheat-code events from URL bar
  useEffect(() => {
    const onCheat = (e) => {
      const key = e.detail;
      if (CHEAT_POPUPS[key]) setPopup(CHEAT_POPUPS[key]);
    };
    window.addEventListener('__cheat', onCheat);
    return () => window.removeEventListener('__cheat', onCheat);
  }, []);

  // Cheat code from URL hash on first load (e.g. visiting /gtaiv directly)
  useEffect(() => {
    const path = (window.location.pathname + window.location.hash).toLowerCase().replace(/^\/+/, '').replace(/[?#].*$/, '');
    if (!path) return;
    // Check cheat codes
    for (const key of ['gtaiv', 'bowling', 'mozaic', 'cousin', 'roman', 'gta']) {
      if (path.includes(key)) {
        const cheatKey = key === 'gta' ? 'gtaiv' : key === 'roman' ? 'cousin' : key;
        setTimeout(() => setPopup(CHEAT_POPUPS[cheatKey]), 600);
        return;
      }
    }
  }, []);

  const current = history[idx];

  const goTo = useCallback((pageId) => {
    if (pageId === current) return;
    setLoadingTarget(pageId);
    setLoading(true);
    setTimeout(() => {
      setHistory((prev) => {
        const next = prev.slice(0, idx + 1);
        next.push(pageId);
        return next;
      });
      setIdx((i) => i + 1);
      setLoading(false);
      setLoadingTarget(null);
      // scroll page to top
      const el = document.querySelector('.page');
      if (el && el.parentElement) el.parentElement.scrollTop = 0;
      window.scrollTo({ top: 0, behavior: 'auto' });
    }, 480);
  }, [current, idx]);

  const onBack = () => {
    if (idx > 0) {
      setLoadingTarget(history[idx - 1]);
      setLoading(true);
      setTimeout(() => { setIdx(i => i - 1); setLoading(false); setLoadingTarget(null); }, 320);
    }
  };
  const onForward = () => {
    if (idx < history.length - 1) {
      setLoadingTarget(history[idx + 1]);
      setLoading(true);
      setTimeout(() => { setIdx(i => i + 1); setLoading(false); setLoadingTarget(null); }, 320);
    }
  };
  const onHome = () => goTo('home');
  const onMail = () => goTo('contact');

  // Robust URL → page mapping. Accepts: project IDs, friendly slugs, full URLs.
  const URL_ROUTES = {
    // Top-level pages
    '': 'home', '/': 'home', 'home': 'home', 'inicio': 'home',
    'contact': 'contact', 'contacto': 'contact',
    'about': 'about', 'acerca': 'about',
    'services': 'services', 'servicios': 'services',
    // Project pages — canonical IDs + friendly slugs
    'aicahealth': 'aicaHealth', 'aica': 'aicaHealth', 'harvard': 'aicaHealth',
    'ductoscnn': 'ductosCnn', 'ypf': 'ductosCnn', 'ductos': 'ductosCnn', 'cnn': 'ductosCnn', 'computervision': 'ductosCnn', 'computer-vision': 'ductosCnn',
    'googlebeta': 'googleBeta', 'google': 'googleBeta', 'browser': 'googleBeta', 'beta': 'googleBeta',
    // Cheat codes
    'gtaiv': '__cheat_gtaiv', 'gta': '__cheat_gtaiv',
    'bowling': '__cheat_bowling',
    'mozaic': '__cheat_mozaic',
    'cousin': '__cheat_cousin',
    'roman': '__cheat_cousin',
  };

  const parseUrl = (val) => {
    // Strip protocol + host, get pathname
    let path = String(val).toLowerCase().trim();
    path = path.replace(/^https?:\/\//, '').replace(/^www\./, '');
    // strip the domain if present
    path = path.replace(/^michelsohn\.dev/, '').replace(/^[^/]*?\.(dev|app)/, '');
    // strip protocol-like remainders + extract first path segment
    path = path.replace(/^\/+/, '').replace(/^.*?\//, '').replace(/\/.*$/, '').replace(/[?#].*$/, '').trim();
    return path;
  };

  const onSubmitUrl = (val) => {
    const slug = parseUrl(val);
    const route = URL_ROUTES[slug];
    if (route && route.startsWith('__cheat_')) {
      const key = route.replace('__cheat_', '');
      setPopup(CHEAT_POPUPS[key]);
      return;
    }
    if (route) return goTo(route);
    return goTo('notFound');
  };

  const labelFor = (id) => {
    if (PAGES[id]) return tweaks.lang === 'es' ? PAGES[id].titleEs : PAGES[id].titleEn;
    if (isProductId(id)) return PRODUCT_DETAILS[id][tweaks.lang].title;
    return '';
  };

  let pageEl;
  if (current === 'home') pageEl = <HomePage tweaks={tweaks} onNav={goTo} lang={tweaks.lang} onPortraitClick={onPortraitClick} />;
  else if (current === 'about') pageEl = <AboutPage onNav={goTo} lang={tweaks.lang} />;
  else if (current === 'contact') pageEl = <ContactPage onNav={goTo} lang={tweaks.lang} />;
  else if (current === 'services') pageEl = <ServicesPage onNav={goTo} lang={tweaks.lang} />;
  else if (current === 'notFound') pageEl = <NotFoundPage onNav={goTo} lang={tweaks.lang} />;
  else if (isProductId(current)) pageEl = <ProductPage id={current} onNav={goTo} lang={tweaks.lang} tweaks={tweaks} />;
  else pageEl = <NotFoundPage onNav={goTo} lang={tweaks.lang} />;

  return (
    <div className={`skin-${tweaks.skin}`}>
      <BrowserChrome
        history={history}
        idx={idx}
        onBack={onBack}
        onForward={onForward}
        onHome={onHome}
        onMail={onMail}
        onSubmitUrl={onSubmitUrl}
        lang={tweaks.lang}
        currentLabel={labelFor(current)}
        loading={loading}
      />
      <div style={{ maxWidth: 1180, margin: '0 auto', padding: '0 0 0' }}>
        <div className="page" style={{ position: 'relative' }} data-screen-label={`Page · ${labelFor(current)}`}>
          {loading && (
            <div className="loading">
              <div>{UI_LABELS[tweaks.lang].pageLoading}<span className="blink">_</span></div>
              <div className="bar"><i></i></div>
              <div style={{ fontSize: 14, color: '#666' }}>www.michelsohn.dev{getUrlSuffix(loadingTarget || current, tweaks.lang)}</div>
            </div>
          )}
          {pageEl}
          <Footer lang={tweaks.lang} visits={visits} onCounterClick={onCounterClick} />
        </div>
      </div>

      {popup && (
        <Popup
          title={popup.title}
          body={popup.body}
          color={popup.color}
          button={tweaks.lang === 'es' ? 'CERRAR' : 'CLOSE'}
          onClose={() => setPopup(null)}
        />
      )}

      {/* Tweaks panel — visible in editor; in production only with ?tweaks=1 */}
      {(typeof window !== 'undefined' && (window.parent !== window || new URLSearchParams(window.location.search).has('tweaks'))) && (
        <TweaksPanel title="Tweaks">
        <TweakSection label={tweaks.lang === 'es' ? 'Apariencia' : 'Appearance'}>
          <TweakRadio
            label={tweaks.lang === 'es' ? 'Skin' : 'Skin'}
            value={tweaks.skin}
            onChange={(v) => setTweak('skin', v)}
            options={[
              { value: 'argentina', label: tweaks.lang === 'es' ? 'Argentina' : 'Argentina' },
              { value: 'rojo', label: tweaks.lang === 'es' ? 'Rojo (homenaje)' : 'Red (homage)' },
              { value: 'azul', label: tweaks.lang === 'es' ? 'Azul profundo' : 'Deep Blue' },
              { value: 'violeta', label: tweaks.lang === 'es' ? 'Violeta' : 'Purple' },
            ]}
          />
          <TweakRadio
            label={tweaks.lang === 'es' ? 'Idioma' : 'Language'}
            value={tweaks.lang}
            onChange={(v) => setTweak('lang', v)}
            options={[
              { value: 'es', label: 'Español' },
              { value: 'en', label: 'English' },
            ]}
          />
        </TweakSection>
        <TweakSection label={tweaks.lang === 'es' ? 'Contenido' : 'Content'}>
          <TweakSlider
            label={tweaks.lang === 'es' ? 'Descuento %' : 'Discount %'}
            value={tweaks.discount}
            onChange={(v) => setTweak('discount', v)}
            min={0}
            max={99}
            step={1}
          />
          <TweakToggle
            label={tweaks.lang === 'es' ? 'Mostrar starburst' : 'Show starburst'}
            value={tweaks.showStarburst}
            onChange={(v) => setTweak('showStarburst', v)}
          />
          <TweakToggle
            label={tweaks.lang === 'es' ? 'Mostrar marquee' : 'Show marquee'}
            value={tweaks.showMarquee}
            onChange={(v) => setTweak('showMarquee', v)}
          />
        </TweakSection>
      </TweaksPanel>
      )}
    </div>
  );
}

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