// Section 04 — System of the day (timeline by daypart)
function SectionDay({ hint = 'plus' }) {
  const [active, setActive] = useState('morning');
  const [openKey, setOpenKey] = useState(null);
  const CAT_LABELS = { coffee: 'Кава', cocoa: 'Какао', matcha: 'Матча', greens: 'Грінс', reds: 'Редс', creamer: 'Вершки', drip: 'Дріп Кава' };
  const CAT_RELABEL = { greens: 'функціональні суміші', reds: 'функціональні суміші' };
  const CAT_NOTE = { cocoa: 'неалкалізоване', matcha: 'церемоніальна', creamer: 'доповнення до гарячих напоїв' };
  const parts = window.MINDME_DAY_PARTS;
  const products = window.MINDME_PRODUCTS;
  const activePart = parts.find(p => p.id === active);
  const activeProducts = activePart.products.map(id => products.find(p => p.id === id));

  return (
    <section className="section" data-screen-label="04 Day system">
      <SectionMeta num="05" label="Лінійка як система дня" />
      <div className="shell">

        {/* Compact headline */}
        <Reveal>
          <div className="day-headline-grid" style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 'clamp(20px, 3vw, 40px)', alignItems: 'last baseline', marginBottom: 'clamp(16px, 2vw, 24px)' }}>
            <h2 className="display" style={{ fontSize: 'clamp(36px, 4vw, 60px)', fontWeight: 800, letterSpacing: '-0.04em', lineHeight: 0.9 }}>
              13<span style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 400, marginLeft: '0.15em' }}>продуктів.</span>
            </h2>
            <p style={{ maxWidth: '52ch', fontSize: 14, lineHeight: 1.5, color: 'var(--ink-soft)' }}>
              Готова функціональна лінійка у ключових форматах щоденного споживання — і сценарії, як вони працюють разом.
            </p>
            <div className="eyebrow" style={{ whiteSpace: 'nowrap' }}>5 моментів дня</div>
          </div>
        </Reveal>

        {/* Daypart tab bar */}
        <Reveal>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span className="eyebrow" style={{ color: 'var(--accent)' }}>Оберіть момент дня</span>
            <span style={{ flex: 1, height: 1, background: 'var(--line)' }} />
            <button onClick={() => { const idx = parts.findIndex(p => p.id === active); setActive(parts[(idx + 1) % parts.length].id); }} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 700, color: '#fff', background: 'var(--accent)', border: 'none', padding: '5px 11px', whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 5 }}
              onMouseEnter={e => { e.currentTarget.style.background = 'var(--ink)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'var(--accent)'; }}>натиснути, щоб переключити <span style={{ fontSize: 12 }}>→</span></button>
          </div>
          <div className="day-tabbar" style={{ display: 'grid', gridTemplateColumns: `repeat(${parts.length}, 1fr)`, borderTop: '1px solid var(--ink)', borderBottom: '1px solid var(--ink)' }}>
            {parts.map((p, i) => {
              const isActive = p.id === active;
              return (
                <button key={p.id} className="daypart-tab" data-active={isActive ? 'true' : 'false'} onClick={() => setActive(p.id)} style={{
                  appearance: 'none',
                  background: isActive ? 'var(--ink)' : 'transparent',
                  color: isActive ? 'var(--bg)' : 'var(--ink)',
                  border: 'none',
                  borderLeft: i > 0 ? '1px solid var(--line)' : 'none',
                  padding: '12px 16px',
                  cursor: 'pointer',
                  textAlign: 'left',
                  fontFamily: 'inherit',
                  position: 'relative',
                  transition: 'background var(--t-fast), color var(--t-fast)',
                }}>
                  <span className="daypart-tab-bar" style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: 'var(--accent)', transform: isActive ? 'scaleX(1)' : 'scaleX(0)', transformOrigin: 'left', transition: 'transform var(--t-fast)' }} />
                  <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', opacity: 0.6, marginBottom: 3 }}>
                    {String(i + 1).padStart(2, '0')} · {p.time}
                  </div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 700, lineHeight: 1, letterSpacing: '-0.02em' }}>{p.label}</div>
                </button>
              );
            })}
          </div>

          {/* Mobile-only timeline rail (variant 4) */}
          <div className="day-rail" style={{ overflowX: 'auto' }}>
            <div style={{ position: 'relative', minWidth: 300, padding: '0 4px' }}>
              <div aria-hidden="true" style={{ position: 'absolute', left: 4, right: 4, top: 8.5, height: 2, background: 'var(--line)' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between', position: 'relative' }}>
                {parts.map((p, i) => {
                  const on = p.id === active;
                  return (
                    <button key={p.id} onClick={() => setActive(p.id)} style={{
                      appearance: 'none', cursor: 'pointer', background: 'transparent', border: 'none', padding: 0,
                      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, flex: 1, minWidth: 0,
                    }}>
                      <span style={{ height: 19, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <span style={{ width: on ? 19 : 13, height: on ? 19 : 13, borderRadius: 999, background: on ? 'var(--accent)' : 'var(--bg)', border: '2px solid ' + (on ? 'var(--accent)' : 'var(--ink-mute)'), transition: 'all var(--t-fast)' }} />
                      </span>
                      <span style={{ fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em', color: on ? 'var(--ink)' : 'var(--ink-mute)', lineHeight: 1 }}>{p.label}</span>
                      <span style={{ fontSize: 9, letterSpacing: '0.03em', color: 'var(--ink-mute)', whiteSpace: 'nowrap' }}>{p.time}</span>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </Reveal>

        {/* Active daypart content — context left + compact product cards right */}
        <div key={activePart.id} style={{ marginTop: 'clamp(18px, 2vw, 28px)', display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 3fr)', gap: 'var(--gap-wide)', alignItems: 'start', animation: 'fadeIn 480ms ease' }}>

          {/* Left: context */}
          <div className="day-context">
            <div className="eyebrow" style={{ marginBottom: 10, color: 'var(--accent)' }}>{activePart.time}</div>
            <h3 className="display" style={{ fontSize: 'clamp(28px, 3vw, 44px)', fontWeight: 700, lineHeight: 1.0, letterSpacing: '-0.025em', marginBottom: 10 }}>{activePart.label}.</h3>
            <p style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink-soft)', maxWidth: '38ch', marginBottom: 14 }}>{activePart.sub}</p>
            <div style={{ fontSize: 12, color: 'var(--ink-mute)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>
              {activeProducts.length} продукт{activeProducts.length === 1 ? '' : (activeProducts.length < 5 ? 'и' : 'ів')}
            </div>
          </div>

          {/* Right: compact product cards */}
          <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.min(activeProducts.length, 4)}, minmax(0, ${activeProducts.length <= 2 ? '240px' : '1fr'}))`, gap: 'var(--gap-tight)', justifyContent: 'start' }}>
            {activeProducts.map((p, idx) => {
              const hoverIng = p.hoverIngredients || (p.ingredients ? p.ingredients.split(',').map(s => ({ name: s.trim(), note: '' })) : []);
              const compareVariants = ['plus', 'ribbon', 'dot', 'always'];
              const compareLabels = { plus: 'Варіант 1 · Кнопка «+»', ribbon: 'Варіант 2 · Стрічка', dot: 'Варіант 3 · Точка «i»', always: 'Варіант 4 · Завжди знизу' };
              const cardHint = hint === 'compare' ? compareVariants[idx % compareVariants.length] : hint;
              return (
              <div key={p.id + activePart.id} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {hint === 'compare' ? (
                  <div style={{ fontSize: 9, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--accent)', textAlign: 'center', minHeight: 12 }}>{compareLabels[cardHint]}</div>
                ) : null}
              <div className={"day-card" + (openKey === (p.id + activePart.id) ? " is-open" : "")}
              onClick={() => setOpenKey(k => k === (p.id + activePart.id) ? null : (p.id + activePart.id))}
              style={{
                background: 'var(--bg)',
                border: '1px solid var(--line)',
                display: 'grid',
                gridTemplateRows: '6px 1fr auto',
                minHeight: 260,
                position: 'relative',
                cursor: 'pointer',
                transition: 'transform var(--t-fast)',
              }}
              onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-3px)'}
              onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}>
                <div style={{ background: p.color }} />
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '14px 10px', background: '#FFFFFF', overflow: 'hidden', position: 'relative' }}>
                  <img src={p.image} alt={p.name} style={{ maxHeight: 140, width: 'auto', objectFit: 'contain' }} />
                  {cardHint === 'plus' ? (
                    <div className="day-card-hint hint-plus" style={{
                      position: 'absolute', bottom: 8, right: 8,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      width: 26, height: 26, borderRadius: 999,
                      background: 'var(--accent)', color: '#fff', fontSize: 17, lineHeight: 1, fontWeight: 400,
                      boxShadow: '0 4px 12px -2px rgba(201,68,42,0.5)',
                    }}>+</div>
                  ) : null}
                  {cardHint === 'dot' ? (
                    <div className="day-card-hint hint-dot" style={{
                      position: 'absolute', top: 8, right: 8,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      width: 18, height: 18, borderRadius: 999,
                      background: 'var(--accent)', color: '#fff', fontSize: 11, fontWeight: 700, fontStyle: 'italic', lineHeight: 1,
                      fontFamily: 'var(--font-serif)',
                    }}>i</div>
                  ) : null}
                  {cardHint === 'ribbon' ? (
                    <div className="day-card-hint hint-ribbon" style={{
                      position: 'absolute', left: 0, right: 0, bottom: 0,
                      background: 'var(--accent)', color: '#fff',
                      fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 700,
                      padding: '6px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    }}>
                      <span>Склад</span><span style={{ fontSize: 12 }}>→</span>
                    </div>
                  ) : null}
                </div>
                <div style={{ padding: '10px 12px 12px', background: 'rgba(10,10,10,0.92)', color: '#F5F1EA' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                    <div style={{ fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.55 }}>{CAT_RELABEL[p.category] || CAT_LABELS[p.category] || p.category}</div>
                    {(p.caffeine || CAT_NOTE[p.category]) ? (
                      <span style={{ fontSize: 8, letterSpacing: '0.05em', textTransform: 'uppercase', fontWeight: 700, color: '#F5F1EA', border: '1px solid rgba(245,241,234,0.35)', borderRadius: 999, padding: '2px 7px', textAlign: 'right', lineHeight: 1.2 }}>{p.caffeine || CAT_NOTE[p.category]}</span>
                    ) : null}
                  </div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 700, lineHeight: 1.1, letterSpacing: '-0.01em' }}>{p.name}</div>
                  <div style={{ marginTop: 3, fontSize: 10.5, opacity: 0.65 }}>{p.role}</div>
                  <div style={{ marginTop: 9, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, borderTop: '1px solid rgba(245,241,234,0.18)', paddingTop: 9 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1 }}>
                      <span style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 800, letterSpacing: '-0.01em' }}>
                        {p.priceMax ? `${p.price}–${p.priceMax}` : p.price}<span style={{ fontSize: 10, marginLeft: 2, opacity: 0.6, fontWeight: 600 }}>грн</span>
                      </span>
                      <span style={{ fontSize: 9.5, opacity: 0.55, marginTop: 2 }}>{p.format}</span>
                    </div>
                    {cardHint === 'always' ? (
                      <div className="day-card-hint hint-always" style={{
                        display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0,
                        fontSize: 9, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 700,
                        color: '#fff', background: 'var(--accent)', borderRadius: 999, padding: '6px 10px',
                      }}>
                        Склад <span style={{ fontSize: 11 }}>→</span>
                      </div>
                    ) : null}
                  </div>
                </div>

                {/* Hover detail overlay */}
                <div className="day-card-overlay" style={{
                  position: 'absolute', inset: 0, background: 'rgba(10,10,10,0.97)', color: '#F5F1EA',
                  padding: '14px 14px 16px', display: 'flex', flexDirection: 'column', gap: 8,
                  opacity: 0, pointerEvents: 'none', transition: 'opacity var(--t-fast)', overflow: 'auto',
                }}>
                  <div style={{ fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.55 }}>{CAT_LABELS[p.category] || p.category} · {p.name}</div>
                  <p style={{ fontSize: 11.5, lineHeight: 1.4 }}>{p.hoverDesc || p.role}</p>
                  {p.activeMg ? (
                    <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--accent)', lineHeight: 1.35 }}>{p.activeMg}</div>
                  ) : null}
                  {p.activeNote ? (
                    <div style={{ fontSize: 9, opacity: 0.55, lineHeight: 1.3 }}>{p.activeNote}</div>
                  ) : null}
                  {hoverIng.length > 0 ? (
                    <div style={{ borderTop: '1px solid rgba(245,241,234,0.18)', paddingTop: 8 }}>
                      <div style={{ fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.55, marginBottom: 6 }}>Ключові інгредієнти</div>
                      <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 5, margin: 0, padding: 0 }}>
                        {hoverIng.map((it, k) => (
                          <li key={k} style={{ fontSize: 10, lineHeight: 1.35 }}>
                            <span style={{ fontWeight: 700 }}>{it.name}</span>{it.note ? <span style={{ opacity: 0.62 }}> — {it.note}</span> : null}
                          </li>
                        ))}
                      </ul>
                    </div>
                  ) : null}
                </div>
              </div>
              </div>
              );
            })}
          </div>
          <div className="day-prod-nav" aria-hidden="true">
            <button type="button" className="why-arrow" aria-label="Попередній" onClick={(e)=>{const s=e.currentTarget.closest('.day-prod-nav').previousElementSibling; s.scrollBy({left:-s.clientWidth*0.72, behavior:'smooth'});}}>←</button>
            <button type="button" className="why-arrow" aria-label="Наступний" onClick={(e)=>{const s=e.currentTarget.closest('.day-prod-nav').previousElementSibling; s.scrollBy({left:s.clientWidth*0.72, behavior:'smooth'});}}>→</button>
          </div>
        </div>

        {/* Lifestyle anchor — wide band at the bottom, always rendered */}
        <Reveal>
          {(() => {
            const fallback = parts.find(p => p.lifestyle);
            const img = activePart.lifestyle || (fallback && fallback.lifestyle);
            const caption = activePart.lifestyle ? activePart.lifestyleCaption : (fallback && fallback.lifestyleCaption);
            if (!img) return null;
            return (
              <figure key={activePart.id + 'life'} style={{ position: 'relative', width: '100%', aspectRatio: '24 / 7', overflow: 'hidden', background: 'var(--bg-alt)', marginTop: 'clamp(18px, 2vw, 28px)' }}>
                <img src={img} alt={caption || activePart.label} style={{
                  position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center',
                }} />
                <figcaption style={{ position: 'absolute', left: 20, right: 20, bottom: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#0A0A0A', fontWeight: 600 }}>
                  <span>{caption}</span>
                  <span>{activePart.time}</span>
                </figcaption>
              </figure>
            );
          })()}
        </Reveal>

        <style>{`
          @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
          .daypart-tab[data-active="false"]:hover { background: var(--bg-alt) !important; }
          .daypart-tab[data-active="false"]:hover .daypart-tab-bar { transform: scaleX(1) !important; opacity: 0.4; }
          .day-card.is-open .day-card-overlay { opacity: 1 !important; pointer-events: auto !important; }
          .day-card-hint { transition: transform var(--t-fast), opacity var(--t-fast); }
          .hint-plus { animation: hintPulse 2.2s ease-in-out infinite; }
          .day-card.is-open .hint-plus { transform: rotate(45deg); animation: none; }
          .hint-dot { animation: hintDot 1.8s ease-in-out infinite; }
          .day-card.is-open .hint-dot, .day-card.is-open .hint-ribbon, .day-card.is-open .hint-always { opacity: 0; animation: none; }
          @media (hover: hover) {
            .day-card:hover .day-card-overlay { opacity: 1 !important; pointer-events: auto !important; }
            .day-card:hover .hint-plus { transform: rotate(45deg); animation: none; }
            .day-card:hover .hint-dot, .day-card:hover .hint-ribbon, .day-card:hover .hint-always { opacity: 0; animation: none; }
          }
          .hint-ribbon span:last-child { transition: transform var(--t-fast); }
          .hint-always span { animation: hintArrow 1.6s ease-in-out infinite; display: inline-block; }
          @keyframes hintPulse { 0%, 100% { transform: scale(1); box-shadow: 0 4px 12px -2px rgba(201,68,42,0.5); } 50% { transform: scale(1.12); box-shadow: 0 6px 18px -2px rgba(201,68,42,0.7); } }
          @keyframes hintDot { 0%, 100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(201,68,42,0.45); } 50% { transform: scale(1.08); box-shadow: 0 0 0 5px rgba(201,68,42,0); } }
          @keyframes hintArrow { 0%, 100% { transform: translateX(0); } 50% { transform: translateX(3px); } }
          @media (prefers-reduced-motion: reduce) { .day-card-hint, .hint-always span { animation: none !important; } }
        `}</style>
      </div>
    </section>
  );
}

window.SectionDay = SectionDay;
