// Main app — header + nav + screen switching + pull-to-refresh + detail overlay

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "primaryColor": "#0A2B63",
  "accentColor": "#F5B01E",
  "density": "regular",
  "dark": false,
  "showHeaderPhoto": true
}/*EDITMODE-END*/;

function HeroHeader({ compact }) {
  // Home usa la imagen vertical (hero-cropped). El resto de tabs usa la imagen horizontal (header-compact).
  if (compact) {
    return (
      <div style={{
        background: '#0A2457',
        position: 'relative', overflow: 'hidden',
        width: '100%',
      }}>
        <img
          src="assets/header-compact.jpg"
          alt="Reale 2027 · Arriba Boca"
          style={{
            width: '100%', height: 'auto', display: 'block',
          }}
        />
      </div>
    );
  }
  // Home: full hero vertical
  return (
    <div style={{
      background: '#0A2457',
      position: 'relative', overflow: 'hidden',
      height: 600,
    }}>
      <img
        src="assets/hero-cropped.png"
        alt="Reale 2027 · Fixture Apertura 2026"
        style={{
          position: 'absolute', inset: 0,
          width: '100%', height: '100%',
          objectFit: 'cover',
          objectPosition: 'center top',
        }}
      />
      {/* Gradiente inferior */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: 200,
        background: 'linear-gradient(180deg, rgba(10,36,87,0) 0%, rgba(8,25,60,0.9) 35%, #081A3C 60%, #081A3C 100%)',
        pointerEvents: 'none',
      }} />
      {/* Overlay de texto */}
      <div style={{
        position: 'absolute', left: 20, right: 20, bottom: 50,
        zIndex: 1,
      }}>
        <div style={{
          fontFamily: '"Archivo Black", system-ui',
          fontSize: 28, color: '#F5B01E', fontWeight: 900,
          lineHeight: 1.05, letterSpacing: -0.5,
          textShadow: '0 2px 8px rgba(0,0,0,0.6)',
        }}>
          Fixture<br />Apertura 2026
        </div>
        <div style={{
          fontSize: 16, color: '#fff', fontWeight: 700,
          marginTop: 8, letterSpacing: -0.1,
          textShadow: '0 2px 6px rgba(0,0,0,0.95), 0 0 14px rgba(0,0,0,0.6)',
        }}>
          seguí a Boca a todos lados
        </div>
      </div>
    </div>
  );
}

function TabBar({ active, onChange }) {
  const tabs = [
    { k: 'home', l: 'HOME' },
    { k: 'fixture', l: 'FIXTURE' },
    { k: 'resultados', l: 'RESULTADOS' },
    { k: 'tabla', l: 'TABLA' },
    { k: 'estadistica', l: 'ESTADISTICAS' },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '12px 14px 14px', gap: 2,
      background: '#fff',
      borderBottom: '1px dashed rgba(0,0,0,0.2)',
    }}>
      {tabs.map(t => {
        const on = active === t.k;
        return (
          <button
            key={t.k}
            type="button"
            onClick={() => onChange(t.k)}
            style={{
              appearance: 'none', border: 'none',
              background: on ? '#0A2B63' : 'transparent',
              color: on ? '#F5B01E' : 'rgba(0,0,0,0.38)',
              fontSize: 10, fontWeight: 800, letterSpacing: 0.5,
              padding: on ? '6px 10px' : '6px 4px',
              borderRadius: 999,
              cursor: 'pointer', fontFamily: 'inherit',
              flex: 'none',
            }}
          >{t.l}</button>
        );
      })}
    </div>
  );
}

function PullIndicator({ pull, refreshing }) {
  const opacity = Math.min(1, pull / 60);
  const rotate = refreshing ? 'spin' : `${pull * 3}deg`;
  return (
    <div style={{
      position: 'absolute', top: pull - 30, left: '50%', transform: 'translateX(-50%)',
      opacity, transition: refreshing ? 'top 0.25s' : 'none',
      zIndex: 4, pointerEvents: 'none',
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: '50%',
        background: '#0A2B63', color: '#F5B01E',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 14, fontWeight: 900,
        animation: refreshing ? 'reale-spin 0.8s linear infinite' : 'none',
        transform: refreshing ? 'none' : `rotate(${pull * 3}deg)`,
        boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
      }}>↻</div>
    </div>
  );
}

function useIsMobile(breakpoint = 600) {
  const [isMobile, setIsMobile] = React.useState(() => {
    if (typeof window === 'undefined') return false;
    return window.matchMedia(`(max-width: ${breakpoint}px)`).matches;
  });
  React.useEffect(() => {
    const mq = window.matchMedia(`(max-width: ${breakpoint}px)`);
    const handler = (e) => setIsMobile(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', handler);
    else mq.addListener(handler);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', handler);
      else mq.removeListener(handler);
    };
  }, [breakpoint]);
  return isMobile;
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [active, setActive] = React.useState('home');
  const [matchDetail, setMatchDetail] = React.useState(null);
  const [newsDetail, setNewsDetail] = React.useState(null);
  const [pull, setPull] = React.useState(0);
  const [refreshing, setRefreshing] = React.useState(false);
  const apiState = window.useApiBootstrap ? window.useApiBootstrap() : { status: 'fallback' };
  const isMobile = useIsMobile(600);
  const scrollRef = React.useRef(null);
  const startY = React.useRef(null);

  const handleMatchClick = (m) => setMatchDetail(m);
  const handleNewsClick = (n) => setNewsDetail(n);

  // Pull-to-refresh
  const onTouchStart = (e) => {
    if (scrollRef.current && scrollRef.current.scrollTop <= 0) {
      startY.current = e.touches[0].clientY;
    }
  };
  const onTouchMove = (e) => {
    if (startY.current == null) return;
    const dy = e.touches[0].clientY - startY.current;
    if (dy > 0 && scrollRef.current.scrollTop <= 0) {
      setPull(Math.min(90, dy * 0.5));
    }
  };
  const onTouchEnd = () => {
    if (pull > 55) {
      setRefreshing(true);
      setPull(60);
      setTimeout(() => { setRefreshing(false); setPull(0); }, 1100);
    } else {
      setPull(0);
    }
    startY.current = null;
  };
  // Mouse (para testear en desktop)
  const onMouseDown = (e) => {
    if (scrollRef.current && scrollRef.current.scrollTop <= 0) {
      startY.current = e.clientY;
      const move = (ev) => {
        if (startY.current == null) return;
        const dy = ev.clientY - startY.current;
        if (dy > 0) setPull(Math.min(90, dy * 0.5));
      };
      const up = () => {
        if (pull > 55) {
          setRefreshing(true);
          setPull(60);
          setTimeout(() => { setRefreshing(false); setPull(0); }, 1100);
        } else {
          setPull(0);
        }
        startY.current = null;
        window.removeEventListener('mousemove', move);
        window.removeEventListener('mouseup', up);
      };
      window.addEventListener('mousemove', move);
      window.addEventListener('mouseup', up);
    }
  };

  const compact = active !== 'home';

  // Contenido principal de la app (lo mismo en mobile y desktop)
  const appContent = (
    <>
      {window.ApiBadge && <window.ApiBadge state={apiState} />}
      <div
        ref={scrollRef}
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
        onMouseDown={onMouseDown}
        style={{
          height: '100%', overflowY: 'auto', overflowX: 'hidden',
          background: '#F2F2F7',
          position: 'relative',
        }}
      >
        <PullIndicator pull={pull} refreshing={refreshing} />
        <div style={{ transform: `translateY(${pull}px)`, transition: pull === 0 ? 'transform 0.25s' : 'none' }}>
          <HeroHeader compact={compact} />
          <div style={{
            background: '#F2F2F7',
            borderRadius: '18px 18px 0 0',
            marginTop: -18,
            paddingTop: 6,
            position: 'relative',
            zIndex: 3,
          }}>
            <div style={{ display: 'flex', justifyContent: 'center', padding: '6px 0 2px' }}>
              <div style={{ width: 34, height: 4, borderRadius: 999, background: 'rgba(0,0,0,0.15)' }} />
            </div>
            <TabBar active={active} onChange={setActive} />
            {active === 'home' && <ScreenHome onMatchClick={handleMatchClick} onNewsClick={handleNewsClick} />}
            {active === 'fixture' && <ScreenFixture onMatchClick={handleMatchClick} />}
            {active === 'resultados' && <ScreenResultados onMatchClick={handleMatchClick} />}
            {active === 'tabla' && <ScreenTabla />}
            {active === 'estadistica' && <ScreenEstadistica />}
          </div>
        </div>

        {matchDetail && <MatchDetail match={matchDetail} onClose={() => setMatchDetail(null)} />}
        {newsDetail && <NewsDetail item={newsDetail} onClose={() => setNewsDetail(null)} />}
      </div>
    </>
  );

  // Mobile: fullscreen sin marco. La app ocupa toda la pantalla del celu.
  if (isMobile) {
    return (
      <div style={{
        position: 'fixed', inset: 0,
        width: '100vw', height: '100dvh',
        background: '#F2F2F7',
        overflow: 'hidden',
      }}>
        {appContent}
      </div>
    );
  }

  // Desktop: marco simulado de iPhone para preview, panel de tweaks
  return (
    <IOSDevice dark={false} width={430} height={932}>
      {appContent}
      <TweaksPanel title="Tweaks — Reale 2027">
        <TweakSection label="Marca" />
        <TweakColor label="Azul primario" value={t.primaryColor} onChange={v => setTweak('primaryColor', v)} />
        <TweakColor label="Dorado acento" value={t.accentColor} onChange={v => setTweak('accentColor', v)} />
        <TweakSection label="Contenido" />
        <TweakToggle label="Foto Reale en home" value={t.showHeaderPhoto} onChange={v => setTweak('showHeaderPhoto', v)} />
        <TweakSection label="Atajos" />
        <TweakButton label="Ir a Fixture" onClick={() => setActive('fixture')} />
        <TweakButton label="Ir a Tabla" onClick={() => setActive('tabla')} secondary />
        <TweakButton label="Abrir Superclásico" onClick={() => setMatchDetail(window.NEXT_MATCH)} secondary />
      </TweaksPanel>
    </IOSDevice>
  );
}

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