// app.jsx — root, layout, API integration

// ────────────────────────────────────────────────────────────
// API helpers
// ────────────────────────────────────────────────────────────
function getToken() { return localStorage.getItem('linko_token'); }

async function apiFetch(path, opts = {}) {
  const res = await fetch(path, {
    ...opts,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${getToken()}`,
      ...(opts.headers || {}),
    },
  });
  if (res.status === 401) {
    localStorage.removeItem('linko_token');
    localStorage.removeItem('linko_handle');
    window.location.href = '/login.html';
    return null;
  }
  return res;
}

// ────────────────────────────────────────────────────────────
// Header
// ────────────────────────────────────────────────────────────
function AppHeader({ handle, saving, saved, onPublish }) {
  const I = window.Icon;

  function logout() {
    localStorage.removeItem('linko_token');
    localStorage.removeItem('linko_handle');
    window.location.href = '/login.html';
  }

  return (
    <header style={{
      padding: '20px 32px', display: 'flex', alignItems: 'center', gap: 20,
      borderBottom: '1px solid var(--line)', background: 'var(--bg)',
      position: 'sticky', top: 0, zIndex: 5,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 9, background: 'var(--ink)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fdfaf3',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="6" r="2.5"/><circle cx="12" cy="18" r="2.5"/>
            <path d="M12 8.5v7"/>
            <circle cx="6" cy="12" r="2"/><circle cx="18" cy="12" r="2"/>
          </svg>
        </div>
        <div>
          <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22, lineHeight: 1, fontStyle: 'italic' }}>Linko</div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase', marginTop: 2 }}>editor</div>
        </div>
      </div>

      <div style={{ flex: 1 }} />

      {/* URL pill */}
      <a
        href={`/p/${handle}`}
        target="_blank"
        rel="noreferrer"
        style={{ textDecoration: 'none' }}
      >
        <div className="mono" style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: 'var(--panel)', border: '1px solid var(--line)',
          padding: '8px 14px', borderRadius: 999, fontSize: 13, color: 'var(--ink-2)',
          cursor: 'pointer',
        }}>
          <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#46a266' }} />
          linko.bio/<span style={{ color: 'var(--ink)', fontWeight: 600 }}>{handle || 'seu.usuario'}</span>
          <I.external size={12} stroke="var(--ink-3)" />
        </div>
      </a>

      {/* Logout */}
      <button
        onClick={logout}
        style={{
          padding: '9px 16px', borderRadius: 999, border: '1px solid var(--line)',
          background: 'var(--panel)', color: 'var(--ink-3)', fontSize: 13, fontWeight: 600,
        }}
      >
        Sair
      </button>

      {/* Publicar */}
      <button
        onClick={onPublish}
        disabled={saving}
        style={{
          padding: '9px 18px', borderRadius: 999,
          background: saved ? '#46a266' : 'var(--ink)',
          color: '#fdfaf3', fontSize: 13, fontWeight: 600,
          display: 'flex', alignItems: 'center', gap: 6,
          opacity: saving ? 0.7 : 1, transition: 'background 300ms',
        }}
      >
        {saving ? 'Salvando…' : saved ? 'Publicado!' : 'Publicar'}
        {!saving && <I.check size={14} stroke="#fdfaf3" />}
      </button>
    </header>
  );
}

// ────────────────────────────────────────────────────────────
// Preview pane
// ────────────────────────────────────────────────────────────
function PreviewPane({ state }) {
  const I = window.Icon;
  const activeLinks = state.links.filter(l => l.active !== false);
  const styleNames = { classic: 'Clássico', bento: 'Bento', catalog: 'Catálogo', mural: 'Mural' };
  const palette = state.paletteId === 'custom'
    ? window.getCustomPalette(state.customColors)
    : window.PALETTES[state.paletteId];

  return (
    <div style={{ position: 'sticky', top: 92, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--ink-3)', fontWeight: 500 }}>
        <span>Preview ao vivo</span>
        <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--ink-3)' }} />
        <span style={{ color: 'var(--ink-2)', fontWeight: 600 }}>{styleNames[state.style]}</span>
        <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--ink-3)' }} />
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 10, height: 10, borderRadius: 3, background: palette.bg, border: `1px solid ${palette.ink}30` }} />
          {palette.name}
        </span>
      </div>

      <window.IOSDevice width={372} height={780} dark={state.paletteId === 'noir'}>
        <div className="preview-scroll" style={{ height: '100%', overflow: 'auto' }}>
          <div style={{ height: 54 }} />
          <window.PublicPage
            profile={state.profile}
            links={activeLinks}
            style={state.style}
            paletteId={state.paletteId}
            background={state.background}
            customColors={state.customColors}
            bentoGap={state.bentoGap ?? 12}
          />
        </div>
      </window.IOSDevice>

      <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textAlign: 'center', maxWidth: 320, lineHeight: 1.5 }}>
        Alterações aparecem aqui imediatamente.<br/>
        Para publicar de verdade, clique em <strong style={{ color: 'var(--ink-2)' }}>Publicar</strong>.
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// App root
// ────────────────────────────────────────────────────────────
function App() {
  const [state, setState] = React.useState(null);
  const [handle, setHandle] = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [loadError, setLoadError] = React.useState(null);

  // Auth guard + load data
  React.useEffect(() => {
    if (!getToken()) {
      window.location.href = '/login.html';
      return;
    }
    apiFetch('/api/me')
      .then(r => r && r.json())
      .then(data => {
        if (!data) return;
        const { _handle, ...pageData } = data;
        setHandle(_handle || '');
        setState(pageData);
        document.getElementById('loading').style.display = 'none';
      })
      .catch(() => setLoadError('Erro ao carregar sua página.'));
  }, []);

  async function publish() {
    setSaving(true);
    setSaved(false);
    try {
      const res = await apiFetch('/api/me', {
        method: 'PUT',
        body: JSON.stringify(state),
      });
      if (res && res.ok) {
        setSaved(true);
        setTimeout(() => setSaved(false), 3000);
      }
    } finally {
      setSaving(false);
    }
  }

  if (loadError) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', flexDirection: 'column', gap: 12, color: 'var(--ink-3)' }}>
        <div>{loadError}</div>
        <button onClick={() => window.location.reload()} style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', textDecoration: 'underline', background: 'none', border: 'none', cursor: 'pointer' }}>
          Tentar novamente
        </button>
      </div>
    );
  }

  if (!state) return null; // loading screen via HTML

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)' }}>
      <AppHeader handle={handle} saving={saving} saved={saved} onPublish={publish} />
      <div style={{
        display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 440px',
        gap: 32, padding: '28px 32px 48px', maxWidth: 1440, margin: '0 auto',
        alignItems: 'flex-start',
      }}>
        <div style={{ minWidth: 0 }}>
          <window.Backoffice state={state} setState={setState} />
        </div>
        <PreviewPane state={state} />
      </div>
    </div>
  );
}

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