// app.jsx — main app + routing + tweaks
const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "motion": "medium",
  "heroVariant": "split",
  "fontWeight": 500,
  "fontStretch": 75
}/*EDITMODE-END*/;

// Reálné case studies — homepage bento má stejné assety, takže nemusíme připravovat jiné obrázky
const ALL_PROJECTS = [
  // známé case studies (mají thumbnaily)
  { id:'tylex',     title:'tylex',         year:'2025', industry:'výroba',     services:['rebranding','webdesign'],          img:'./assets/case-tylex.jpg' },
  { id:'zabiny',    title:'žabiny brno',   year:'2024', industry:'sport',      services:['identity','kampaň','social'],      img:'./assets/case-zabiny.jpg' },
  { id:'adrick',    title:'adrick',        year:'2024', industry:'b2b',        services:['strategy','brand'],                img:'./assets/case-adrick.jpg' },
  { id:'domoplan',  title:'domoplan',      year:'2023', industry:'reality',    services:['rebranding','webdesign'],          img:'./assets/case-domoplan.png', cls:'card--coral' },
  { id:'huust',     title:'huust',         year:'2023', industry:'tech',       services:['brand','webdesign'],               img:'./assets/case-huust.png',    cls:'card--paper' },
  // další klienti — bez thumbnailu (mockup karta)
  { id:'rohlik',    title:'rohlík',        year:'2023', industry:'e-commerce', services:['social','content'] },
  { id:'kara',      title:'kara',          year:'2022', industry:'móda',       services:['rebranding'],                       cls:'card--paper' },
  { id:'momax',     title:'momax',         year:'2024', industry:'e-commerce', services:['webdesign','strategy'] },
  { id:'seznam',    title:'seznam.cz',     year:'2023', industry:'tech',       services:['kampaň'] },
  { id:'livesport', title:'livesport',     year:'2024', industry:'sport',      services:['brand','identity'],                 cls:'card--coral' },
  { id:'medvistik', title:'medvistík',     year:'2022', industry:'startup',    services:['identity','webdesign'] },
  { id:'rockaway',  title:'rockaway',      year:'2023', industry:'b2b',        services:['brand'] },
  { id:'aukro',     title:'aukro',         year:'2022', industry:'e-commerce', services:['rebranding','webdesign'],           cls:'card--paper' },
  { id:'flowmon',   title:'flowmon',       year:'2023', industry:'tech',       services:['webdesign'] },
  { id:'kaucuk',    title:'kaučuk',        year:'2024', industry:'výroba',     services:['identity','strategy'],              cls:'card--coral' },
];

// Homepage rytmus = (b-1 8×4) + (b-2 4×4) + (b-3/4/5 4×3 každý)
// = 1 hero + 1 vysoká + 3 menší. Opakujeme po 5 dlaždicích.
const BENTO_PATTERN = ['b-1','b-2','b-3','b-4','b-5'];

const SERVICE_FILTERS = ['vše','strategy','brand','identity','rebranding','webdesign','kampaň','social','content','copy','video'];
const INDUSTRY_FILTERS = ['vše','b2b','tech','reality','sport','e-commerce','výroba','móda','startup'];

// --- FilterBar -----------------------------------------------------------
// Kompaktní bar: živé počty per-chip, sliding indicator, single-line.
function FilterBar({ svc, setSvc, ind, setInd, all, filtered }) {
  const svcRef = React.useRef(null);
  const indRef = React.useRef(null);
  const [svcPill, setSvcPill] = React.useState(null);
  const [indPill, setIndPill] = React.useState(null);

  // counts per chip — respect the OTHER axis so čísla žijí
  const svcCount = (s) => all.filter(p =>
    (s === 'vše' || p.services.includes(s)) &&
    (ind === 'vše' || p.industry === ind)
  ).length;
  const indCount = (i) => all.filter(p =>
    (i === 'vše' || p.industry === i) &&
    (svc === 'vše' || p.services.includes(svc))
  ).length;

  // measure active chip → position the sliding pill
  const measure = (rootRef, value, setter) => {
    const root = rootRef.current;
    if (!root) return;
    const el = root.querySelector(`[data-val="${value}"]`);
    if (!el) return;
    const r1 = root.getBoundingClientRect();
    const r2 = el.getBoundingClientRect();
    setter({ left: r2.left - r1.left, top: r2.top - r1.top, width: r2.width, height: r2.height });
  };

  const remeasure = React.useCallback(() => {
    measure(svcRef, svc, setSvcPill);
    measure(indRef, ind, setIndPill);
  }, [svc, ind]);

  React.useLayoutEffect(() => { remeasure(); }, [remeasure]);

  // re-measure once webfonts are ready (the initial 'vše' chip would mis-size before)
  React.useEffect(() => {
    if (document.fonts && document.fonts.ready) {
      document.fonts.ready.then(() => remeasure());
    }
    const t1 = setTimeout(remeasure, 60);
    const t2 = setTimeout(remeasure, 240);
    window.addEventListener('resize', remeasure);
    return () => { clearTimeout(t1); clearTimeout(t2); window.removeEventListener('resize', remeasure); };
  }, [remeasure]);

  const isFiltered = svc !== 'vše' || ind !== 'vše';
  const reset = () => { setSvc('vše'); setInd('vše'); };

  const renderRow = (label, items, value, setValue, countFn, rootRef, pill) => (
    <div className="fbar__row">
      <span className="fbar__lbl">{label}</span>
      <div className="fbar__chips" ref={rootRef}>
        {pill && (
          <span
            className="fbar__pill"
            style={{
              transform: `translate(${pill.left}px, ${pill.top}px)`,
              width: pill.width,
              height: pill.height,
            }}
          />
        )}
        {items.map(s => {
          const n = countFn(s);
          const dim = n === 0 && s !== 'vše';
          return (
            <button
              key={s}
              data-val={s}
              className={'fchip ' + (value === s ? 'is-on ' : '') + (dim ? 'is-dim' : '')}
              onClick={() => setValue(s)}
              disabled={dim}
            >
              <span className="fchip__txt">{s}</span>
              <span className="fchip__n">{n}</span>
            </button>
          );
        })}
      </div>
    </div>
  );

  return (
    <div className="fbar" data-reveal>
      {renderRow('služba', SERVICE_FILTERS, svc, setSvc, svcCount, svcRef, svcPill)}
      {renderRow('obor', INDUSTRY_FILTERS, ind, setInd, indCount, indRef, indPill)}
      <div className="fbar__meta">
        <span className="fbar__count">
          <strong key={filtered.length}>{String(filtered.length).padStart(2,'0')}</strong>
          <span>/ {ALL_PROJECTS.length} projektů</span>
        </span>
        {isFiltered && (
          <button className="fbar__clear" onClick={reset} title="reset filtrů">
            reset <span aria-hidden>✕</span>
          </button>
        )}
      </div>
    </div>
  );
}

function ProjectsPage({ onNav }) {
  useReveal();
  const [svc, setSvc] = useStateApp('vše');
  const [ind, setInd] = useStateApp('vše');
  const filtered = ALL_PROJECTS.filter(p =>
    (svc==='vše' || p.services.includes(svc)) &&
    (ind==='vše' || p.industry===ind)
  );
  return (
    <>
      <section className="page-hero" data-screen-label="P1 Projekty Hero">
        <img className="stone-deco" src="./assets/stone-render-1.png" alt="" style={{
          right:-80,top:-40,width:380,opacity:.4,transform:'rotate(20deg)'
        }} />
        <div className="shell" style={{padding:0,position:'relative'}}>
          <h1 data-reveal>projekty<span style={{color:'var(--coral)'}}>.</span></h1>
          <p data-reveal style={{"--reveal-delay":"160ms",maxWidth:'52ch',color:'#bdbdbd',marginTop:24,fontSize:17}}>
            500+ projektů za 12 let. Tady je výběr, na který jsme hrdí — od rebrandů a webů po dlouhodobé kampaně. Filtruj podle oboru nebo služby.
          </p>
        </div>
      </section>
      <section data-screen-label="P1 Projekty Filter" style={{padding:'0 36px',maxWidth:1440,margin:'0 auto',width:'100%'}}>
        <FilterBar
          svc={svc} setSvc={setSvc}
          ind={ind} setInd={setInd}
          all={ALL_PROJECTS}
          filtered={filtered}
        />
      </section>
      <section className="proj-grid proj-grid--bento" data-screen-label="P1 Projekty Grid">
        {filtered.map((p,i)=>{
          const bentoClass = BENTO_PATTERN[i % BENTO_PATTERN.length];
          return (
            <article
              key={p.id}
              className={"card " + bentoClass + ' ' + (p.cls||'')}
              data-reveal
              onClick={() => onNav && onNav('case')}
              style={Object.assign({cursor:'pointer'}, p.img?{backgroundImage:`url(${p.img})`,backgroundSize:'cover',backgroundPosition:'center'}:{})}
            >
              {p.img && <div className="card__shade" />}
              <span className="card__num">{String(i+1).padStart(2,'0')} / case</span>
              <div className="card__body">
                <div className="card__tags">
                  {p.services.slice(0,3).map((s,j)=>(<span key={j} className="card__tag">{s}</span>))}
                </div>
                <h3 className="card__title">{p.title}</h3>
                <p className="card__sub">{p.year} · {p.industry}</p>
              </div>
            </article>
          );
        })}
        {filtered.length===0 && (
          <div style={{gridColumn:'1 / -1',padding:'80px 24px',textAlign:'center',color:'var(--muted)',fontSize:18}}>
            Žádné projekty pro tuto kombinaci. Zkus jiný filtr — nebo nám rovnou napiš.
          </div>
        )}
      </section>
      <Clients />
      <Contact />
      <Footer />
    </>
  );
}

function ServicesPage({ onNav }) {
  useReveal();
  const SVCP_FLOW = window.SVCP_FLOW;
  const [activeId, setActiveId] = useStateApp(SVCP_FLOW[0].id);
  const active = SVCP_FLOW.find(x => x.id === activeId);

  return (
    <>
      <window.SvcMapHero onNav={onNav} />
      <window.ServicesFlat onNav={onNav} />

      <JustaskBaliky />
      <Justask />
      <window.ServicesCrossroads onNav={onNav} />
      <Contact />
      <Footer />
    </>
  );
}

function HomePage({ heroVariant, onNav }) {
  useReveal();
  return (
    <>
      <Hero variant={heroVariant} />
      <Intro />
      <Clients />
      <Projects onNav={onNav} />
      <Services />
      <Justask />
      <Crossroads onNav={onNav} />
      <Contact />
      <Footer />
    </>
  );
}

const MOTION_LABELS = { low:'Málo', medium:'Středně', high:'Hodně' };
const HERO_LABELS = { split:'Split', stacked:'Stack', marquee:'Marquee' };

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [page, setPage] = useStateApp('home');

  // apply motion class to body
  useEffectApp(() => {
    document.body.classList.remove('motion-low','motion-medium','motion-high');
    document.body.classList.add('motion-' + tweaks.motion);
  }, [tweaks.motion]);

  // apply font weight/stretch as CSS vars
  useEffectApp(() => {
    document.documentElement.style.setProperty('--display-weight', tweaks.fontWeight);
    document.documentElement.style.setProperty('--display-stretch', tweaks.fontStretch + '%');
    // Apply to display headings
    const css = `
      .h-display, .hero__word:not(.hero__word--outline), .footer__big, .page-hero h1 {
        font-weight: ${tweaks.fontWeight};
        font-stretch: ${tweaks.fontStretch}%;
      }`;
    let s = document.getElementById('jm-tweak-style');
    if (!s) { s = document.createElement('style'); s.id='jm-tweak-style'; document.head.appendChild(s); }
    s.textContent = css;
  }, [tweaks.fontWeight, tweaks.fontStretch]);

  // page change → scroll top
  useEffectApp(() => { window.scrollTo({top:0,behavior:'instant'}); }, [page]);

  const onNav = (target, anchor) => {
    setPage(target);
    window.__appNav = (t,a) => { setPage(t); if(a){setTimeout(()=>{const e=document.getElementById(a);if(e)e.scrollIntoView({behavior:'smooth',block:'start'})},80)}};
    if (anchor) {
      setTimeout(()=>{
        const el = document.getElementById(anchor);
        if (el) el.scrollIntoView({behavior:'smooth',block:'start'});
      }, 80);
    }
  };

  return (
    <>
      <Nav onNav={onNav} page={page} />
      {page === 'home' && <HomePage heroVariant={tweaks.heroVariant} onNav={onNav} />}
      {page === 'projekty' && <ProjectsPage onNav={onNav} />}
      {page === 'sluzby' && <ServicesPage onNav={onNav} />}
      {page === 'justask' && <JustaskPage />}
      {page === 'kariera' && <KarieraPage onNav={onNav} />}
      {page === 'kontakt' && <KontaktPage />}
      {page === 'knowhub' && <KnowhubPage onNav={onNav} />}
      {page === 'knowhub-category' && <KhCategoryPage onNav={onNav} />}
      {page === 'knowhub-event' && <KhEventPage onNav={onNav} />}
      {page === 'onas' && <window.OnasPage onNav={onNav} />}
      {page === 'case' && <window.CasePage onNav={onNav} />}
      {page === 'kh-mom' && <window.MomPage onNav={onNav} />}
      {window.KH_STUB_IDS && window.KH_STUB_IDS.includes(page) && page !== 'kh-mom' && <window.KhStubPage page={page} onNav={onNav} />}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Animace" />
        <TweakRadio
          label="Síla"
          value={tweaks.motion}
          options={['low','medium','high']}
          onChange={(v)=>setTweak('motion',v)}
        />
        <TweakSection label="Hero varianta" />
        <TweakRadio
          label="Layout"
          value={tweaks.heroVariant}
          options={['split','stacked','marquee']}
          onChange={(v)=>setTweak('heroVariant',v)}
        />
        <TweakSection label="Typografie" />
        <TweakSlider label="Váha" min={200} max={900} step={100} value={tweaks.fontWeight} onChange={(v)=>setTweak('fontWeight',v)} />
        <TweakSlider label="Stretch" min={75} max={125} step={5} value={tweaks.fontStretch} onChange={(v)=>setTweak('fontStretch',v)} unit="%" />
      </TweaksPanel>
    </>
  );
}

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