// features.jsx — feature tour with animated iPhone screens
// Four tabs: Today, Library, Routine, Journal. Auto-cycles + click-to-switch.

const { useState: useFState, useEffect: useFEffect, useRef: useFRef } = React;

function Features({ motion = true }) {
  const tabs = [
    { id: 'today',   label: 'Today',   tag: 'Daily check-in',     italic: "How's your skin today?" },
    { id: 'library', label: 'Library', tag: 'Ingredient lookup',  italic: "Efficacy meets ecology." },
    { id: 'routine', label: 'Routine', tag: 'AM / PM builder',    italic: "What plays well together." },
    { id: 'journal', label: 'Journal', tag: 'Longitudinal record', italic: "Memory, not metrics." },
  ];

  const [active, setActive] = useFState(0);

  // Auto-cycle every 6 seconds
  useFEffect(() => {
    if (!motion) return;
    const id = setInterval(() => setActive((a) => (a + 1) % tabs.length), 6000);
    return () => clearInterval(id);
  }, [motion]);

  return (
    <section id="features" className="section" style={{ position: 'relative' }}>
      <div className="container">
        <div style={{
          display: 'flex', alignItems: 'baseline', gap: 16,
          marginBottom: 'clamp(28px, 4vh, 48px)',
        }}>
          <span className="eyebrow">§ 02 · The app</span>
          <span style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
          <span className="lab">5 tabs · iPhone-only</span>
        </div>

        <h2 className="display-3 text-balance" style={{
          margin: 0, maxWidth: 880,
        }}>
          A field journal{' '}
          <span className="serif-italic" style={{ color: 'var(--moss-deep)' }}>for your skin.</span>
          {' '}Four surfaces, one ecosystem.
        </h2>
      </div>

      <div className="container" style={{ marginTop: 'clamp(60px, 8vh, 100px)' }}>
        <div className="feature-grid" style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1.05fr',
          gap: 'clamp(40px, 5vw, 80px)',
          alignItems: 'center',
        }}>
          {/* LEFT — tabs + descriptive text */}
          <div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {tabs.map((t, i) => (
                <TabRow
                  key={t.id}
                  tab={t}
                  active={i === active}
                  onClick={() => setActive(i)}
                />
              ))}
            </div>
          </div>

          {/* RIGHT — iPhone with active screen */}
          <div style={{
            position: 'relative',
            display: 'flex', justifyContent: 'center',
            minHeight: 720,
          }}>
            {/* halo */}
            <div style={{
              position: 'absolute', top: '50%', left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 480, height: 480, borderRadius: '50%',
              background: 'radial-gradient(circle, rgba(127,179,160,0.25), transparent 60%)',
              filter: 'blur(40px)', pointerEvents: 'none',
              animation: motion ? 'breathe 6s ease-in-out infinite' : 'none',
            }} />

            <IPhone width={340} label={tabs[active].label.toLowerCase()}>
              <div style={{ position: 'absolute', inset: 0 }}>
                {active === 0 && <ScreenToday motion={motion} />}
                {active === 1 && <ScreenLibrary motion={motion} />}
                {active === 2 && <ScreenRoutine motion={motion} />}
                {active === 3 && <ScreenJournal motion={motion} />}
              </div>
            </IPhone>

            {/* Floating tab badge */}
            <div style={{
              position: 'absolute',
              top: 24, right: 0,
              padding: '10px 14px',
              borderRadius: 14,
              background: 'var(--glass)',
              border: '0.5px solid var(--glass-edge)',
              backdropFilter: 'blur(14px)',
              WebkitBackdropFilter: 'blur(14px)',
              fontSize: 11, fontFamily: 'var(--font-mono)',
              letterSpacing: '0.12em', textTransform: 'uppercase',
              color: 'var(--moss-deep)',
              boxShadow: '0 12px 28px -12px rgba(61,107,87,0.3)',
            }}>
              tab {active + 1} / {tabs.length} · {tabs[active].label}
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 1240px) {
          .feature-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

function TabRow({ tab, active, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        textAlign: 'left',
        background: active ? 'rgba(255,255,255,0.7)' : 'transparent',
        border: 'none',
        borderLeft: `2px solid ${active ? 'var(--moss)' : 'transparent'}`,
        padding: '20px 24px',
        borderRadius: 0,
        cursor: 'pointer',
        transition: 'all .4s cubic-bezier(.16,.84,.32,1)',
        fontFamily: 'inherit',
        color: 'inherit',
      }}
      onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'rgba(255,255,255,0.4)'; }}
      onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
    >
      <div className="lab" style={{ color: 'var(--moss-deep)' }}>
        {tab.tag}
      </div>
      <h3 style={{
        margin: '4px 0 0',
        fontFamily: 'var(--font-display)',
        fontSize: 36, fontWeight: 400,
        letterSpacing: '-0.018em',
        lineHeight: 1.05,
        color: active ? 'var(--ink)' : 'var(--ink-faint)',
        transition: 'color .4s ease',
      }}>{tab.label}</h3>
      <div className="serif-italic" style={{
        marginTop: 4,
        fontSize: 18,
        color: active ? 'var(--moss-deep)' : 'var(--ink-faint)',
        transition: 'color .4s ease',
        lineHeight: 1.3,
      }}>{tab.italic}</div>
      {active && (
        <p className="body-m" style={{
          margin: '14px 0 0',
          maxWidth: 460,
          color: 'var(--ink-soft)',
          animation: 'fade-text .6s ease both',
        }}>
          {tab.id === 'today' && "Today's check-in, your skin's recent trend, the Microbiome Minute and this week's Note. Nothing else."}
          {tab.id === 'library' && "Search or browse the full ingredient library by category. Two grades, a plain-language summary and citations."}
          {tab.id === 'routine' && "Drag-to-reorder AM and PM stacks. Conflict notes appear inline (retinoid × AHA, vitamin C × niacinamide handling)."}
          {tab.id === 'journal' && "Tap any past entry to see the feeling, flags, context, products and any photos attached. 30-day history free; Plus unlimited."}
          <style>{`@keyframes fade-text { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; } }`}</style>
        </p>
      )}
    </button>
  );
}

/* ────────────────────────────────────────────────────────────────
   APP SCREENS — pastel, editorial, in-frame
   ──────────────────────────────────────────────────────────────── */

const screenBase = {
  position: 'absolute', inset: 0, paddingTop: 56,
  fontFamily: 'system-ui, -apple-system, sans-serif',
  color: '#1B2823',
};

function ScreenToday({ motion }) {
  return (
    <div style={{ ...screenBase, background: 'linear-gradient(180deg, #E5F0E8 0%, #F4F8F4 60%)' }}>
      <div style={{ padding: '8px 22px 16px' }}>
        <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', letterSpacing: '0.14em', textTransform: 'uppercase', color: '#5A9985' }}>Tuesday · 26 May</div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 30, lineHeight: 1.05, margin: '4px 0 0', letterSpacing: '-0.02em' }}>
          Good morning.
        </h1>
      </div>

      {/* Microbiome Minute card */}
      <div style={{
        margin: '0 16px',
        background: '#FFFFFF',
        borderRadius: 22,
        padding: 18,
        boxShadow: '0 8px 24px -10px rgba(61,107,87,0.18)',
        border: '0.5px solid rgba(127,179,160,0.2)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: '#5A9985', letterSpacing: '0.14em', textTransform: 'uppercase' }}>Minute</div>
          <div style={{ fontSize: 10, color: '#9aa4a0' }}>1 min</div>
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, lineHeight: 1.15, margin: '6px 0 8px', letterSpacing: '-0.01em' }}>
          Why your skin <i>changes</i> at 4pm.
        </div>
        <div style={{ fontSize: 11, color: '#5b6663', lineHeight: 1.45 }}>
          Sebum production runs on a circadian rhythm — your t-zone tends to get oilier as the day goes on…
        </div>
        {/* tiny illustration */}
        <div style={{ marginTop: 10, height: 44, borderRadius: 10, background: 'linear-gradient(180deg, #F0DCD0, #FBEFEA)', position: 'relative', overflow: 'hidden' }}>
          <svg viewBox="0 0 200 60" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
            <path d="M 0 50 Q 50 10 100 30 T 200 20" fill="none" stroke="#E8B8C5" strokeWidth="2" />
            {[20, 70, 120, 170].map((x, i) => (
              <circle key={i} cx={x} cy={30 + (i%2)*10} r="3" fill="#E8A89C" />
            ))}
          </svg>
        </div>
      </div>

      {/* Check-in card */}
      <div style={{
        margin: '14px 16px 0',
        background: 'linear-gradient(160deg, #7FB3A0, #5A9985)',
        borderRadius: 22,
        padding: 18,
        color: '#F4F8F4',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.7 }}>Daily Check-in · 10 sec</div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, lineHeight: 1.15, margin: '8px 0 14px', letterSpacing: '-0.01em' }}>
          How's your skin today?
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {['Great','Fine','Off','Rough'].map((f, i) => (
            <button key={f} style={{
              flex: 1, padding: '10px 0',
              borderRadius: 12, border: '0.5px solid rgba(244,248,244,0.4)',
              background: i === 1 ? 'rgba(244,248,244,0.95)' : 'rgba(244,248,244,0.12)',
              color: i === 1 ? '#3D6B57' : '#F4F8F4',
              fontSize: 12, fontWeight: 500,
              animation: motion && i === 1 ? 'pulse-pick 2.4s ease-in-out infinite' : 'none',
            }}>{f}</button>
          ))}
        </div>
        {/* Decoration */}
        <svg viewBox="0 0 100 100" style={{ position: 'absolute', right: -20, bottom: -20, width: 90, opacity: 0.25 }}>
          <circle cx="50" cy="50" r="40" fill="#F4F8F4" />
          <circle cx="40" cy="42" r="10" fill="#D9E8C9" />
          <circle cx="58" cy="56" r="14" fill="#D9E8C9" opacity="0.6" />
        </svg>
        <style>{`
          @keyframes pulse-pick {
            0%, 100% { box-shadow: 0 0 0 0 rgba(244,248,244,0.5); }
            50%      { box-shadow: 0 0 0 8px rgba(244,248,244,0); }
          }
        `}</style>
      </div>

      {/* Tab bar */}
      <AppTabBar active="today" />
    </div>
  );
}

function ScreenLibrary({ motion }) {
  const items = [
    { name: 'Niacinamide', cat: 'cell-signalling', eff: 'tier 1', bio: 'supportive', col: '#7FB3A0' },
    { name: 'Retinaldehyde', cat: 'retinoid', eff: 'tier 1', bio: 'neutral', col: '#E8C896' },
    { name: 'Salicylic acid', cat: 'BHA', eff: 'tier 1', bio: 'neutral', col: '#E8C896' },
    { name: 'Squalane', cat: 'occlusive', eff: 'tier 2', bio: 'supportive', col: '#7FB3A0' },
    { name: 'SLS', cat: 'surfactant', eff: 'tier 3', bio: 'disruptive', col: '#E8A89C' },
  ];
  return (
    <div style={{ ...screenBase, background: '#F4F8F4' }}>
      <div style={{ padding: '8px 22px 14px' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 30, lineHeight: 1.05, margin: 0, letterSpacing: '-0.02em' }}>Library</h1>
        <div style={{ fontSize: 11, color: '#6b746f', marginTop: 2 }}>470+ ingredients · efficacy × microbiome</div>
        <div style={{
          marginTop: 14, padding: '9px 14px',
          background: '#FFFFFF', borderRadius: 14,
          border: '0.5px solid rgba(127,179,160,0.25)',
          fontSize: 13, color: '#6b746f',
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><circle cx="7" cy="7" r="5" stroke="#5A9985" strokeWidth="1.4" /><path d="M11 11l3 3" stroke="#5A9985" strokeWidth="1.4" strokeLinecap="round" /></svg>
          Search ingredients
        </div>
      </div>
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map((it, i) => (
          <div key={it.name} style={{
            background: '#FFFFFF', borderRadius: 16, padding: '12px 14px',
            display: 'flex', alignItems: 'center', gap: 12,
            border: '0.5px solid rgba(127,179,160,0.18)',
            animation: motion ? `slide-in .6s cubic-bezier(.16,.84,.32,1) ${i*0.08}s both` : 'none',
          }}>
            <div style={{
              width: 38, height: 38, borderRadius: 10,
              background: `radial-gradient(circle at 35% 30%, #FFF, ${it.col})`,
              border: `0.5px solid ${it.col}`,
            }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{it.name}</div>
              <div style={{ fontSize: 10, color: '#9aa4a0', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{it.cat}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'flex-end' }}>
              <span style={{ fontSize: 9, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', color: '#3D6B57', background: '#E5F0E8', padding: '2px 6px', borderRadius: 4 }}>{it.eff}</span>
              <span style={{ fontSize: 9, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', color: it.col === '#E8A89C' ? '#A85A5A' : '#3D6B57' }}>{it.bio}</span>
            </div>
          </div>
        ))}
      </div>
      <AppTabBar active="library" />
      <style>{`
        @keyframes slide-in { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; } }
      `}</style>
    </div>
  );
}

function ScreenRoutine({ motion }) {
  return (
    <div style={{ ...screenBase, background: '#F4F8F4' }}>
      <div style={{ padding: '8px 22px 14px' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 30, lineHeight: 1.05, margin: 0, letterSpacing: '-0.02em' }}>Routine</h1>
      </div>
      {/* AM / PM toggle */}
      <div style={{ display: 'flex', margin: '0 16px', padding: 4, background: '#E5F0E8', borderRadius: 12 }}>
        {['AM','PM'].map((t, i) => (
          <div key={t} style={{
            flex: 1, textAlign: 'center', padding: '8px 0',
            borderRadius: 9, background: i === 0 ? '#FFFFFF' : 'transparent',
            fontSize: 12, fontWeight: 500, color: i === 0 ? '#3D6B57' : '#6b746f',
            boxShadow: i === 0 ? '0 1px 2px rgba(0,0,0,0.08)' : 'none',
          }}>{t}</div>
        ))}
      </div>

      <div style={{ padding: '16px 16px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[
          { step: 'Cleanse', name: 'Gentle hydrating cleanser', col: '#B8D4C2' },
          { step: 'Treat',   name: 'Niacinamide 10%', col: '#D9E8C9' },
          { step: 'Moisture', name: 'Ceramide barrier cream', col: '#F0DCD0' },
          { step: 'Protect', name: 'Mineral SPF 50', col: '#E8C896' },
        ].map((s, i) => (
          <div key={s.step} style={{
            background: '#FFFFFF', borderRadius: 16, padding: 12,
            display: 'flex', alignItems: 'center', gap: 12,
            border: '0.5px solid rgba(127,179,160,0.18)',
            animation: motion ? `slide-in-r .6s cubic-bezier(.16,.84,.32,1) ${i*0.1}s both` : 'none',
          }}>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 22, color: '#5A9985', width: 28, textAlign: 'center' }}>{i+1}</div>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: `radial-gradient(circle at 30% 30%, #FFF, ${s.col})`, border: `0.5px solid ${s.col}` }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10, color: '#5A9985', fontFamily: 'var(--font-mono)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>{s.step}</div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{s.name}</div>
            </div>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M3 4h8M3 7h8M3 10h8" stroke="#9aa4a0" strokeWidth="1.4" strokeLinecap="round" />
            </svg>
          </div>
        ))}

        {/* Conflict note */}
        <div style={{
          marginTop: 6, padding: '10px 12px',
          background: 'rgba(232,200,150,0.18)',
          borderRadius: 12, border: '0.5px dashed rgba(200,160,90,0.4)',
          fontSize: 11, color: '#7a5e2a', display: 'flex', gap: 8, alignItems: 'flex-start',
        }}>
          <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', color: '#a07d35', fontSize: 15, lineHeight: 1 }}>i</div>
          <div>
            <b style={{ fontWeight: 500 }}>Heads up:</b> Niacinamide & vitamin C are best in <i style={{ fontFamily: 'var(--font-display)' }}>separate routines</i> if your barrier feels fragile.
          </div>
        </div>
      </div>
      <AppTabBar active="routine" />
      <style>{`@keyframes slide-in-r { from { opacity: 0; transform: translateX(-12px); } to { opacity: 1; } }`}</style>
    </div>
  );
}

function ScreenJournal({ motion }) {
  const entries = [
    { day: 'Today',   feeling: 'fine',   col: '#D9E8C9', note: 'pH 5.4, slept 7h, no flags' },
    { day: 'Yesterday', feeling: 'off',  col: '#F0DCD0', note: 'tightness · introduced retinal' },
    { day: 'Sun',     feeling: 'great',  col: '#B8D4C2', note: 'rest day, double cleanse' },
    { day: 'Sat',     feeling: 'fine',   col: '#D9E8C9', note: 'humid · light routine' },
    { day: 'Fri',     feeling: 'rough',  col: '#E8A89C', note: 'breakout · stress 4/5' },
  ];
  return (
    <div style={{ ...screenBase, background: '#F4F8F4' }}>
      <div style={{ padding: '8px 22px 8px' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 30, lineHeight: 1.05, margin: 0, letterSpacing: '-0.02em' }}>Journal</h1>
        <div style={{ fontSize: 11, color: '#6b746f', marginTop: 2 }}>5-day streak — wait, never mind.</div>
      </div>

      {/* Tiny chart */}
      <div style={{ margin: '8px 16px 14px', height: 60, background: '#FFFFFF', borderRadius: 14, border: '0.5px solid rgba(127,179,160,0.2)', position: 'relative', overflow: 'hidden', padding: 8 }}>
        <svg viewBox="0 0 300 50" style={{ width: '100%', height: '100%' }}>
          <path d="M 0 30 L 50 20 L 100 25 L 150 40 L 200 15 L 250 22 L 300 10" fill="none" stroke="#7FB3A0" strokeWidth="2" />
          {[0,50,100,150,200,250,300].map((x,i) => {
            const ys = [30,20,25,40,15,22,10];
            return <circle key={i} cx={x} cy={ys[i]} r="3" fill="#7FB3A0" />;
          })}
          <path d="M 0 30 L 50 20 L 100 25 L 150 40 L 200 15 L 250 22 L 300 10 L 300 50 L 0 50 Z" fill="#7FB3A0" fillOpacity="0.12" />
        </svg>
      </div>

      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {entries.map((e, i) => (
          <div key={e.day} style={{
            background: '#FFFFFF', borderRadius: 14, padding: '12px 14px',
            display: 'flex', alignItems: 'center', gap: 12,
            border: '0.5px solid rgba(127,179,160,0.18)',
            animation: motion ? `slide-in-j .5s cubic-bezier(.16,.84,.32,1) ${i*0.06}s both` : 'none',
          }}>
            <div style={{ width: 28, height: 28, borderRadius: '50%', background: e.col, border: '0.5px solid rgba(0,0,0,0.05)' }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 500 }}>{e.day}</div>
              <div style={{ fontSize: 10, color: '#6b746f' }}>{e.note}</div>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 16, color: '#5A9985' }}>{e.feeling}</div>
          </div>
        ))}
      </div>
      <AppTabBar active="journal" />
      <style>{`@keyframes slide-in-j { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; } }`}</style>
    </div>
  );
}

function AppTabBar({ active }) {
  const tabs = [
    ['today', 'Today', 'M9 22V12h6v10'],
    ['library', 'Library', 'M4 5h16v14H4z M9 5v14'],
    ['routine', 'Routine', 'M4 7h16M4 12h16M4 17h10'],
    ['journal', 'Journal', 'M6 4h10l4 4v12H6z'],
    ['settings', 'Settings', 'M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8'],
  ];
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0,
      background: 'rgba(244,248,244,0.95)',
      backdropFilter: 'blur(20px) saturate(160%)',
      WebkitBackdropFilter: 'blur(20px) saturate(160%)',
      borderTop: '0.5px solid rgba(127,179,160,0.2)',
      padding: '10px 0 28px',
      display: 'flex', justifyContent: 'space-around',
    }}>
      {tabs.map(([id, label, d]) => (
        <div key={id} style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          color: id === active ? '#3D6B57' : '#9aa4a0',
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
            <path d={d} stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          <div style={{ fontSize: 9, fontWeight: 500 }}>{label}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Features, ScreenToday, ScreenLibrary, ScreenRoutine, ScreenJournal, AppTabBar });
