const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentColor": "#7B68EE",
  "mintColor": "#00CDA0",
  "bgColor": "#0B0914"
}/*EDITMODE-END*/;

/* ── FOOTER ── */
const Footer = ({ navigate }) => (
  <footer className="footer">
    <div className="container">
      <div className="footer-grid">
        <div>
          <button className="nav-logo" onClick={() => navigate('home')}
            style={{ marginBottom: 20 }}>
            <div className="nav-logo-mark">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                stroke="#fff" strokeWidth="2.2" strokeLinecap="round">
                <circle cx="12" cy="12" r="10"/>
                <path d="M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20M2 12h20"/>
              </svg>
            </div>
            VELA
          </button>
          <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.75, maxWidth: 280 }}>
            A Dubai-based studio crafting websites and mobile apps for businesses
            worldwide. From corner shops to global institutions.
          </p>
        </div>

        <div>
          <div className="footer-col-title">Services</div>
          {['Restaurant & Hospitality','Retail & E-Commerce','Professional Services','Institutions','Mobile Apps'].map(s => (
            <button key={s} className="footer-link" onClick={() => navigate('services')}>{s}</button>
          ))}
        </div>

        <div>
          <div className="footer-col-title">Company</div>
          {[['Our Work','work'],['Process','process'],['Pricing','pricing'],['Contact','contact']].map(([l,p]) => (
            <button key={p} className="footer-link" onClick={() => navigate(p)}>{l}</button>
          ))}
        </div>

        <div>
          <div className="footer-col-title">Connect</div>
          <a className="footer-link" href="mailto:velawebdesign@gmail.com">Email</a>
          <a className="footer-link" href="tel:+971585930425">+971 58 593 0425</a>
          <a className="footer-link"
            href="https://wa.me/971585930425" target="_blank" rel="noopener">WhatsApp</a>
          <a className="footer-link" href="#" style={{ opacity: 0.5, cursor: 'default' }}>LinkedIn (soon)</a>
        </div>
      </div>

      <div className="footer-bottom">
        <span>© 2026 VELA. All rights reserved.</span>
        <span>Dubai · Global</span>
      </div>
    </div>
  </footer>
);

/* ── TWEAKS PANEL ── */
const TweaksPanel = ({ visible, tweaks, setTweaks }) => {
  if (!visible) return null;
  const set = (key, val) => {
    const next = { ...tweaks, [key]: val };
    setTweaks(next);
    document.documentElement.style.setProperty('--accent', next.accentColor);
    document.documentElement.style.setProperty('--accent-glow', next.accentColor + '40');
    document.documentElement.style.setProperty('--accent-dim', next.accentColor + '20');
    document.documentElement.style.setProperty('--accent-rgb',
      parseInt(next.accentColor.slice(1,3),16) + ',' +
      parseInt(next.accentColor.slice(3,5),16) + ',' +
      parseInt(next.accentColor.slice(5,7),16));
    document.documentElement.style.setProperty('--mint', next.mintColor);
    document.documentElement.style.setProperty('--mint-dim', next.mintColor + '20');
    document.documentElement.style.setProperty('--bg', next.bgColor);
    document.body.style.background = next.bgColor;
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
  };

  const sliderStyle = { width: '100%', cursor: 'pointer', accentColor: tweaks.accentColor };

  return (
    <div style={{
      position: 'fixed', bottom: 90, right: 24, zIndex: 1000,
      background: 'var(--card)', border: '1px solid var(--border)',
      borderRadius: 14, padding: '20px 20px 16px',
      width: 240,
      boxShadow: '0 16px 48px rgba(0,0,0,0.5)',
      animation: 'slideDown 0.2s ease',
    }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: 2.5, color: 'var(--muted)', marginBottom: 16 }}>
        TWEAKS
      </div>

      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 6 }}>Accent Color</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {['#7B68EE','#E85D75','#F59E0B','#10B981','#3B82F6'].map(c => (
            <div key={c} onClick={() => set('accentColor', c)} style={{
              width: 22, height: 22, borderRadius: '50%', background: c,
              cursor: 'pointer', flexShrink: 0,
              border: tweaks.accentColor === c ? '2px solid #fff' : '2px solid transparent',
              transition: 'border-color 0.2s',
            }} />
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 6 }}>Mint / Highlight</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {['#00CDA0','#22D3EE','#A78BFA','#FB923C','#F472B6'].map(c => (
            <div key={c} onClick={() => set('mintColor', c)} style={{
              width: 22, height: 22, borderRadius: '50%', background: c,
              cursor: 'pointer', flexShrink: 0,
              border: tweaks.mintColor === c ? '2px solid #fff' : '2px solid transparent',
              transition: 'border-color 0.2s',
            }} />
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 8 }}>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 6 }}>Background</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {['#0B0914','#090909','#0A0F14','#0C0A0A','#080D0B'].map(c => (
            <div key={c} onClick={() => set('bgColor', c)} style={{
              width: 22, height: 22, borderRadius: '50%', background: c,
              cursor: 'pointer', flexShrink: 0,
              border: tweaks.bgColor === c ? '2px solid var(--accent)' : '1px solid var(--border)',
              transition: 'border-color 0.2s',
            }} />
          ))}
        </div>
      </div>
    </div>
  );
};

/* ── APP ── */
const App = () => {
  const [page, setPage]             = useState(() => localStorage.getItem('vela-page') || 'home');
  const [fading, setFading]         = useState(false);
  const [tweaksOn, setTweaksOn]     = useState(false);
  const [tweaks, setTweaks]         = useState(TWEAK_DEFAULTS);

  // Persist page
  const navigate = (newPage) => {
    if (newPage === page) return;
    setFading(true);
    setTimeout(() => {
      setPage(newPage);
      localStorage.setItem('vela-page', newPage);
      window.scrollTo({ top: 0, behavior: 'instant' });
      setFading(false);
    }, 260);
  };

  // Tweaks host protocol
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode')   setTweaksOn(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOn(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  // Apply saved tweaks to CSS vars on mount
  useEffect(() => {
    document.documentElement.style.setProperty('--accent', tweaks.accentColor);
    document.documentElement.style.setProperty('--accent-glow', tweaks.accentColor + '40');
    document.documentElement.style.setProperty('--accent-dim', tweaks.accentColor + '20');
    document.documentElement.style.setProperty('--mint', tweaks.mintColor);
    document.documentElement.style.setProperty('--mint-dim', tweaks.mintColor + '20');
    document.documentElement.style.setProperty('--bg', tweaks.bgColor);
    document.body.style.background = tweaks.bgColor;
  }, []);

  // Scroll reveal — re-run on page change
  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('visible'); });
    }, { threshold: 0.08 });
    const timer = setTimeout(() => {
      document.querySelectorAll('.reveal').forEach(el => {
        el.classList.remove('visible');
        obs.observe(el);
      });
    }, 80);
    return () => { clearTimeout(timer); obs.disconnect(); };
  }, [page]);

  const PAGES = {
    home:     window.HomePage,
    services: window.ServicesPage,
    work:     window.WorkPage,
    process:  window.ProcessPage,
    pricing:  window.PricingPage,
    contact:  window.ContactPage,
  };
  const PageComponent = PAGES[page] || window.HomePage;

  return (
    <div style={{
      opacity:    fading ? 0 : 1,
      transform:  fading ? 'translateY(10px)' : 'translateY(0)',
      transition: 'opacity 0.26s ease, transform 0.26s ease',
      minHeight: '100vh',
    }}>
      <window.VelaNav currentPage={page} navigate={navigate} />

      <main style={{ paddingTop: 'var(--nav-h)' }}>
        <PageComponent navigate={navigate} />
      </main>

      <Footer navigate={navigate} />

      {/* WhatsApp */}
      <a className="wa-btn"
        href="https://wa.me/971585930425?text=Hi%2C%20I'm%20interested%20in%20a%20project%20with%20VELA"
        target="_blank" rel="noopener" aria-label="Chat on WhatsApp">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="white">
          <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/>
          <path d="M12 0C5.373 0 0 5.373 0 12c0 2.025.506 3.94 1.395 5.617L.048 23.395a.5.5 0 0 0 .607.607l5.778-1.347A11.95 11.95 0 0 0 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 22c-1.862 0-3.628-.5-5.153-1.393l-.36-.214-3.733.87.886-3.733-.235-.374A9.96 9.96 0 0 1 2 12c0-5.514 4.486-10 10-10s10 4.486 10 10-4.486 10-10 10z"/>
        </svg>
      </a>

      <TweaksPanel visible={tweaksOn} tweaks={tweaks} setTweaks={setTweaks} />
    </div>
  );
};

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