// Vanta App — shell: navigation + composition. Screens: home | area:<key> | sources.

function VantaApp() {
  const data = window.VANTA_DATA;
  const A = data.areas;
  const [store, update] = useVantaStore();
  const [screen, setScreen] = React.useState('home');
  const [habitsOpen, setHabitsOpen] = React.useState(false);
  const [expandedKey, setExpandedKey] = React.useState(null);
  const [arranging, setArranging] = React.useState(false);
  const [restOpen, setRestOpen] = React.useState(false);
  const scrollRef = React.useRef(null);

  const P = window.GARDEN_PALETTES[store.palette] || window.GARDEN_PALETTES.dusk;
  const S = vStyles(P);

  const cyclePalette = () => {
    const order = window.GARDEN_PALETTE_ORDER;
    update(s => ({ palette: order[(order.indexOf(s.palette) + 1) % order.length] }));
  };

  const go = (s) => { setScreen(s); if (scrollRef.current) scrollRef.current.scrollTop = 0; };

  // Live thoughts headline
  const todayThoughts = store.thoughts.filter(t => Date.now() - t.ts < 86400000).length;
  const thoughtsArea = {
    ...A.thoughts,
    headline: todayThoughts > 0 ? `${todayThoughts} today` : A.thoughts.headline,
    sub: store.thoughts[0] ? `last planted ${vantaAgo(store.thoughts[0].ts)}` : A.thoughts.sub,
  };

  // User-arranged order (shared with desktop); mobile hides the habits key —
  // it has its own dedicated card here.
  const order = vantaCardOrder(store.cardOrder).filter(k => k !== 'habits');
  const visible = order.filter(k => !store.hidden[k]);

  return (
    <React.Fragment>
    <div ref={scrollRef} style={{
      height: '100%', overflowY: 'auto', boxSizing: 'border-box', position: 'relative',
      background: `radial-gradient(600px 500px at 30% -5%, ${P.bg2}, ${P.bg} 60%)`,
      color: P.ink,
      fontFamily: '"Bricolage Grotesque", ui-sans-serif, system-ui, sans-serif',
      fontSize: 13, lineHeight: 1.45,
      display: 'flex', flexDirection: 'column',
      transform: arranging ? 'scale(0.9)' : 'none',
      opacity: arranging ? 0.35 : 1,
      transition: 'transform .3s cubic-bezier(.4,0,.2,1), opacity .3s ease',
      transformOrigin: '50% 15%',
    }}>
      {screen === 'home' && (
        <React.Fragment>
          <div style={{ flex: 1 }}>
            <VHomeHeader P={P} palette={store.palette} onCyclePalette={cyclePalette} onSources={() => go('sources')} onArrange={() => setArranging(true)} />
            <VReflection data={data} P={P} />
            <VHorizon P={P} value={store.horizon} onChange={(h) => update({ horizon: h })} />
            {store.horizon !== 'today' && <VHorizonPanel P={P} horizon={store.horizon} />}
            {store.horizon !== 'today' && <VHabitsCard P={P} data={data} store={store} onOpen={() => setHabitsOpen(true)} />}
            {store.horizon === 'today' && (
              <React.Fragment>
                {/* The task list is the primary daily surface — give it the full
                    width; the habits card sits below as a horizontal card. */}
                <VMoves P={P} store={store} update={update} />
                <VHabitsCard P={P} data={data} store={store} onOpen={() => setHabitsOpen(true)} />
              </React.Fragment>
            )}
            {store.horizon === 'today' && <VRhythm P={P} />}
            {(() => {
              // Smart-open (Level 2), mirrored from desktop: the first two areas
              // and anything notable today stay full; the quiet rest fold into
              // one strip you expand on demand. The depth chip flips all open.
              const areaFor = (k) => (k === 'thoughts' ? thoughtsArea : A[k]);
              const depth = store.depth || 'smart';
              const renderArea = (k) => (
                <VAreaCard
                  key={k} area={areaFor(k)} areaKey={k} data={data} P={P} store={store} update={update}
                  expanded={expandedKey === k} onToggle={() => setExpandedKey(expandedKey === k ? null : k)}
                />
              );
              const { notable, resting } = vPartitionAreas(visible, areaFor, (k) => store.lastTouch[k] || 0, depth, 2);
              return (
                <div style={{ margin: '14px 20px 0' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
                    <span style={{ ...S.caps, color: P.ink4 }}>your areas</span>
                    <button onClick={() => update({ depth: depth === 'open' ? 'smart' : 'open' })} style={{
                      appearance: 'none', border: 0, background: 'transparent', color: P.ink3,
                      fontFamily: 'inherit', fontSize: 11, letterSpacing: '0.06em', cursor: 'pointer', padding: 0,
                    }}>{depth === 'open' ? 'showing all · calm it' : 'smart view · show all'}</button>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    {notable.map(renderArea)}
                  </div>
                  {resting.length > 0 && (
                    <div style={{ marginTop: 12 }}>
                      <button onClick={() => setRestOpen(o => !o)} style={{
                        appearance: 'none', border: 0, cursor: 'pointer', width: '100%', textAlign: 'left', boxSizing: 'border-box',
                        background: P.tile, borderRadius: 18, padding: '12px 16px', fontFamily: 'inherit',
                        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, color: P.ink2,
                      }}>
                        <span style={{ ...S.serif, fontSize: 15, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                          {resting.length} area{resting.length === 1 ? '' : 's'} resting
                          <span style={{ ...S.caps, color: P.ink4, marginLeft: 8 }}>{resting.map(k => areaFor(k).label.toLowerCase()).join(' · ')}</span>
                        </span>
                        <span style={{ ...S.caps, color: P.ink3, flex: '0 0 auto' }}>{restOpen ? 'tuck ↑' : 'tend ↓'}</span>
                      </button>
                      {restOpen && (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 12 }}>
                          {resting.map(renderArea)}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })()}
            <VThemes goals={A.goals} P={P} />
            <div style={{ height: 8 }} />
          </div>
          <VPlantBar P={P} store={store} update={update} />
        </React.Fragment>
      )}

      {screen === 'sources' && (
        <VSourcesScreen data={data} P={P} store={store} update={update} onBack={() => go('home')} />
      )}

      {habitsOpen && (
        <VHabitsSheet P={P} data={data} store={store} update={update} onClose={() => setHabitsOpen(false)} />
      )}
    </div>

    {arranging && (
      <VArrange
        P={P}
        order={vantaCardOrder(store.cardOrder)}
        labels={Object.fromEntries(Object.entries(A).map(([k, a]) => [k, a.label]))}
        onDone={(next) => { update({ cardOrder: next }); setArranging(false); }}
        onCancel={() => setArranging(false)}
      />
    )}
    </React.Fragment>
  );
}

window.VantaApp = VantaApp;
