// Main app shell — full pregnancy companion, mobile-first.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "rose",
  "logScale": false,
  "showBands": true,
  "fontSize": 15
}/*EDITMODE-END*/;

function applyPalette(p) {
  const pal = window.PALETTES[p] || window.PALETTES.rose;
  document.documentElement.style.setProperty('--accent', pal.accent);
  document.documentElement.style.setProperty('--accent-soft', pal.soft);
  document.documentElement.style.setProperty('--accent-ink', pal.ink);
}
function applyFontSize(px) {
  document.documentElement.style.setProperty('--fs', `${px}px`);
  document.documentElement.style.fontSize = `${px}px`;
}
function useIsMobile() {
  const [m, setM] = React.useState(() => window.innerWidth <= 700);
  React.useEffect(() => {
    const fn = () => setM(window.innerWidth <= 700);
    window.addEventListener('resize', fn);
    return () => window.removeEventListener('resize', fn);
  }, []);
  return m;
}

const NAV_ITEMS = [
  { id:'home',         zh:'首頁',   en:'Home',        icon:'🌸' },
  { id:'hcg',          zh:'HCG',    en:'HCG',         icon:'📈' },
  { id:'kicks',        zh:'胎動',   en:'Kicks',       icon:'👶' },
  { id:'contractions', zh:'宮縮',   en:'Contractions',icon:'⏱' },
  { id:'checklist',    zh:'清單',   en:'Checklist',   icon:'✅' },
];

function App() {
  const isMobile = useIsMobile();
  const [page, setPage] = React.useState(() => localStorage.getItem('app_page') || 'home');
  const [tweaks, setTweaks] = React.useState(() => {
    try { return { ...TWEAK_DEFAULTS, ...JSON.parse(localStorage.getItem('app_tweaks') || '{}') }; }
    catch(e) { return TWEAK_DEFAULTS; }
  });
  const [editMode, setEditMode] = React.useState(false);

  const navigate = (p) => {
    setPage(p);
    localStorage.setItem('app_page', p);
  };

  React.useEffect(() => {
    const fn = (e) => {
      if (e.data?.type === '__activate_edit_mode') setEditMode(true);
      if (e.data?.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', fn);
    try { window.parent.postMessage({ type:'__edit_mode_available' }, '*'); } catch(e) {}
    return () => window.removeEventListener('message', fn);
  }, []);

  React.useEffect(() => { applyPalette(tweaks.palette); }, [tweaks.palette]);
  React.useEffect(() => { applyFontSize(tweaks.fontSize); }, [tweaks.fontSize]);

  const handleTweaks = (next) => {
    setTweaks(next);
    localStorage.setItem('app_tweaks', JSON.stringify(next));
  };

  const pageTitle = NAV_ITEMS.find(n => n.id === page);

  const renderPage = () => {
    switch(page) {
      case 'home':         return <HomePage onNavigate={navigate} />;
      case 'hcg':          return <HcgPage tweaks={tweaks} />;
      case 'kicks':        return <KicksPage />;
      case 'contractions': return <ContractionsPage />;
      case 'checklist':    return <ChecklistPage />;
      default:             return <HomePage onNavigate={navigate} />;
    }
  };

  if (isMobile) {
    return (
      <div style={{ minHeight:'100vh', display:'flex', flexDirection:'column', background:'var(--bg)' }}>
        {/* Mobile header */}
        <header style={{
          position:'sticky', top:0, zIndex:20,
          background:'var(--card)',
          borderBottom:'1px solid var(--line)',
          padding:'12px 16px 10px',
          display:'flex', alignItems:'center', gap:10,
        }}>
          <div style={{ fontSize:20 }}>{pageTitle?.icon}</div>
          <div>
            <div className="serif" style={{ fontSize:18, fontWeight:600, lineHeight:1 }}>
              {pageTitle?.zh}
            </div>
            <div className="en" style={{ fontSize:9.5, letterSpacing:'0.06em' }}>{pageTitle?.en}</div>
          </div>
          <div style={{ marginLeft:'auto' }}>
            <div className="serif" style={{
              fontSize:13, color:'var(--accent)', fontStyle:'italic', fontWeight:500,
            }}>孕程陪伴</div>
          </div>
        </header>

        {/* Page content */}
        <div style={{ flex:1, overflowY:'auto', paddingBottom:'env(safe-area-inset-bottom,0px)' }}>
          {renderPage()}
        </div>

        {/* Bottom nav */}
        <nav style={{
          position:'fixed', bottom:0, left:0, right:0, zIndex:30,
          background:'var(--card)',
          borderTop:'1px solid var(--line)',
          display:'grid', gridTemplateColumns:`repeat(${NAV_ITEMS.length},1fr)`,
          paddingBottom:'env(safe-area-inset-bottom,4px)',
        }}>
          {NAV_ITEMS.map(n => (
            <button key={n.id} className="btn-reset" onClick={() => navigate(n.id)} style={{
              padding:'9px 0 7px',
              display:'flex', flexDirection:'column', alignItems:'center', gap:2,
              borderTop: page===n.id ? `2px solid var(--accent)` : '2px solid transparent',
              background: page===n.id ? 'var(--accent-soft)' : 'transparent',
              color: page===n.id ? 'var(--accent-ink)' : 'var(--ink-faint)',
              transition:'all 0.12s',
            }}>
              <span style={{ fontSize:17, lineHeight:1 }}>{n.icon}</span>
              <span style={{ fontSize:9.5, letterSpacing:'0.02em', fontWeight: page===n.id ? 600 : 400 }}>
                {n.zh}
              </span>
            </button>
          ))}
        </nav>

        <TweaksPanel visible={editMode} tweaks={tweaks} onTweaks={handleTweaks} />
      </div>
    );
  }

  // ── Desktop ──────────────────────────────────────────────────────────────
  return (
    <div style={{ display:'flex', height:'100vh', overflow:'hidden', background:'var(--bg)' }}>
      <DesktopSidebar activePage={page} onNavigate={navigate} />

      {/* Main content */}
      <main style={{ flex:1, overflowY:'auto', height:'100vh', padding:'32px 32px 80px' }}>
        {/* Page header */}
        <div style={{ marginBottom:24 }}>
          <div style={{ display:'flex', alignItems:'baseline', gap:12 }}>
            <span style={{ fontSize:28 }}>{pageTitle?.icon}</span>
            <div className="serif" style={{ fontSize:34, fontWeight:500, letterSpacing:'-0.02em', lineHeight:1 }}>
              {pageTitle?.zh}
            </div>
            <div className="serif" style={{ fontSize:18, color:'var(--ink-soft)', fontStyle:'italic' }}>
              {pageTitle?.en}
            </div>
          </div>
        </div>
        {renderPage()}
      </main>

      <TweaksPanel visible={editMode} tweaks={tweaks} onTweaks={handleTweaks} />
    </div>
  );
}

function DesktopSidebar({ activePage, onNavigate }) {
  return (
    <aside style={{
      width:220, flexShrink:0,
      background:'var(--card)',
      borderRight:'1px solid var(--line)',
      height:'100vh',
      display:'flex', flexDirection:'column',
      overflowY:'auto',
      padding:'28px 0 20px',
    }}>
      <div style={{ padding:'0 20px 24px' }}>
        <div className="serif" style={{ fontSize:24, fontWeight:500, letterSpacing:'-0.02em', lineHeight:1 }}>
          孕程陪伴
        </div>
        <div className="en" style={{ fontSize:10.5, color:'var(--ink-faint)', marginTop:3 }}>
          Pregnancy Companion
        </div>
      </div>

      <nav style={{ flex:1 }}>
        {NAV_ITEMS.map(n => {
          const isActive = activePage === n.id;
          return (
            <button key={n.id} className="btn-reset" onClick={() => onNavigate(n.id)} style={{
              width:'100%', padding:'11px 20px',
              display:'flex', alignItems:'center', gap:12,
              background: isActive ? 'var(--accent-soft)' : 'transparent',
              borderLeft: isActive ? '3px solid var(--accent)' : '3px solid transparent',
              color: isActive ? 'var(--accent-ink)' : 'var(--ink-soft)',
              fontWeight: isActive ? 600 : 400,
              fontSize:13, transition:'all 0.12s', textAlign:'left',
            }}>
              <span style={{ fontSize:18, width:24, textAlign:'center' }}>{n.icon}</span>
              <div>
                <div>{n.zh}</div>
                <div className="en" style={{ fontSize:9.5, opacity:0.7, letterSpacing:'0.05em' }}>{n.en}</div>
              </div>
            </button>
          );
        })}
      </nav>

      <div style={{ padding:'16px 20px 0', borderTop:'1px solid var(--line)' }}>
        <div style={{ fontSize:10, color:'var(--ink-faint)', lineHeight:1.6 }}>
          ※ 本工具僅供參考，不代替醫療建議。<br/>
          <span className="en">Not a substitute for medical advice.</span>
        </div>
      </div>
    </aside>
  );
}

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