/* global React, Icon, Pill, fmt,
   TASKS, STATUS_META, PAUTA_MONTH,
   loadNotes, saveNotes */
const { useState: useStateM, useEffect: useEffectM, useMemo: useMemoM } = React;

/* ============================================================
   MORNING · primeira tela do time · visual rico
   ============================================================ */
const VERSES = [
  { text: 'Tudo posso naquele que me fortalece.', ref: 'Filipenses 4:13' },
  { text: 'O Senhor é o meu pastor; nada me faltará.', ref: 'Salmos 23:1' },
  { text: 'Confia no Senhor de todo o teu coração.', ref: 'Provérbios 3:5' },
  { text: 'Esforça-te e tem bom ânimo.', ref: 'Josué 1:9' },
  { text: 'Buscai primeiro o Reino de Deus.', ref: 'Mateus 6:33' },
  { text: 'O que estiver ao alcance da tua mão para fazer, faze-o conforme as tuas forças.', ref: 'Eclesiastes 9:10' },
  { text: 'Cada dia tem o seu próprio mal.', ref: 'Mateus 6:34' },
  { text: 'Tudo tem o seu tempo determinado, e há tempo para todo o propósito.', ref: 'Eclesiastes 3:1' },
  { text: 'A alegria do Senhor é a vossa força.', ref: 'Neemias 8:10' },
  { text: 'O coração alegre serve de bom remédio.', ref: 'Provérbios 17:22' },
];

const MOODS = [
  { id: 'energia',  emoji: '⚡', label: 'Cheio de energia', color: '#6FC878' },
  { id: 'foco',     emoji: '🎯', label: 'Em foco',          color: '#9A9BE5' },
  { id: 'tranquilo',emoji: '🌿', label: 'Tranquilo',         color: '#77B8F1' },
  { id: 'criativo', emoji: '🎨', label: 'Criativo',          color: '#F3AE4D' },
  { id: 'cansado',  emoji: '☕', label: 'Cansado',           color: '#8B89A3' },
  { id: 'ansioso',  emoji: '🌀', label: 'Ansioso',           color: '#C7C6D7' },
];

const MOOD_LS_KEY = 'beza_morning_mood_v1';

function MorningView({ viewer, onGoToPauta }) {
  const verseIdx = (PAUTA_MONTH?.todayDay || 1) % VERSES.length;
  const verse = VERSES[verseIdx];

  const todayKey = `${PAUTA_MONTH?.year}-${PAUTA_MONTH?.todayDay}-${viewer.id}`;
  const [moodMap, setMoodMap] = useStateM(() => {
    try { return JSON.parse(localStorage.getItem(MOOD_LS_KEY) || '{}'); } catch { return {}; }
  });
  useEffectM(() => { try { localStorage.setItem(MOOD_LS_KEY, JSON.stringify(moodMap)); } catch (e) {} }, [moodMap]);
  const currentMood = moodMap[todayKey];
  const setMood = (id) => setMoodMap(prev => ({ ...prev, [todayKey]: id }));

  // Animação de gradiente em tempo real (suave)
  const [tick, setTick] = useStateM(0);
  useEffectM(() => {
    const id = setInterval(() => setTick(t => (t + 1) % 360), 80);
    return () => clearInterval(id);
  }, []);

  const hour = new Date().getHours();
  const greeting = hour < 6 ? 'Boa madrugada' : hour < 12 ? 'Bom dia' : hour < 18 ? 'Boa tarde' : 'Boa noite';
  const timeEmoji = hour < 6 ? '🌙' : hour < 12 ? '☀' : hour < 18 ? '☀' : '🌙';

  const today = PAUTA_MONTH?.todayDay || 13;
  const myToday = TASKS.filter(t => t.assignee === viewer.id && t.dueDay === today && !['publicado', 'aprovacao'].includes(t.status));
  const myLate  = TASKS.filter(t => t.assignee === viewer.id && t.status === 'atrasada');
  const myAhead = TASKS.filter(t => t.assignee === viewer.id && t.dueDay > today && t.dueDay <= today + 3 && t.status === 'a-fazer');

  const priorities = [...myLate.slice(0, 2), ...myToday, ...myAhead].slice(0, 4);

  const [draft, setDraft] = useStateM('');
  const [savedNote, setSavedNote] = useStateM(false);

  const saveQuickNote = () => {
    if (!draft.trim()) return;
    const notes = loadNotes ? loadNotes() : {};
    const existing = notes[viewer.id] || '';
    const stamp = new Date().toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
    const updated = `[${stamp}] ${draft.trim()}\n\n${existing}`;
    if (saveNotes) saveNotes({ ...notes, [viewer.id]: updated });
    setDraft('');
    setSavedNote(true);
    setTimeout(() => setSavedNote(false), 2200);
  };

  return (
    <div style={{ padding: '0 0 var(--space-7)' }}>
      {/* HERO grande · saudação como protagonista absoluta */}
      <section style={{
        position: 'relative',
        minHeight: '78vh',
        padding: 'var(--space-8) var(--space-6) var(--space-7)',
        marginTop: 'calc(var(--space-6) * -1)',
        marginLeft: 'calc(var(--space-5) * -1)',
        marginRight: 'calc(var(--space-5) * -1)',
        background: `linear-gradient(${tick}deg, rgba(154,155,229,0.18), rgba(120,121,201,0.10) 45%, rgba(199,198,215,0.12) 100%)`,
        overflow: 'hidden',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {/* Blobs gigantes animados · aurora */}
        <div aria-hidden="true" style={{
          position: 'absolute', top: '-30%', left: '-10%',
          width: '60vw', height: '60vw', borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(154,155,229,0.40), transparent 60%)',
          filter: 'blur(80px)', pointerEvents: 'none',
          animation: 'morningDriftA 24s var(--ease-in-out) infinite',
        }} />
        <div aria-hidden="true" style={{
          position: 'absolute', bottom: '-30%', right: '-15%',
          width: '70vw', height: '70vw', borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(120,121,201,0.32), transparent 60%)',
          filter: 'blur(90px)', pointerEvents: 'none',
          animation: 'morningDriftB 32s var(--ease-in-out) infinite reverse',
        }} />
        <div aria-hidden="true" style={{
          position: 'absolute', top: '30%', right: '20%',
          width: '40vw', height: '40vw', borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(199,198,215,0.22), transparent 60%)',
          filter: 'blur(70px)', pointerEvents: 'none',
          animation: 'morningDriftC 38s var(--ease-in-out) infinite',
        }} />

        <div style={{
          position: 'relative', zIndex: 1,
          maxWidth: 1080, width: '100%',
          textAlign: 'center',
          animation: 'morningEnter 1.2s var(--ease-out)',
        }}>
          {/* Data sutil em cima */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '6px 14px',
            background: 'rgba(255,255,255,0.45)',
            backdropFilter: 'blur(12px)',
            border: '1px solid rgba(154,155,229,0.30)',
            borderRadius: 999,
            fontSize: 12, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
            color: 'var(--accent)',
            marginBottom: 36,
          }}>
            <span style={{ fontSize: 14 }}>{timeEmoji}</span>
            {dateLabel()}
          </div>

          {/* SAUDAÇÃO COLOSSAL */}
          <h1 style={{
            margin: '0 0 var(--space-3)',
            fontSize: 'clamp(56px, 12vw, 156px)',
            fontWeight: 300,
            letterSpacing: '-0.04em',
            lineHeight: 0.92,
            color: 'var(--text)',
          }}>
            <span style={{ opacity: 0.65 }}>{greeting}, </span>
            <br />
            <span style={{
              fontWeight: 500,
              background: 'linear-gradient(135deg, var(--beza-purple), var(--beza-deep))',
              WebkitBackgroundClip: 'text',
              backgroundClip: 'text',
              color: 'transparent',
              display: 'inline-block',
            }}>{viewer.name}</span>
            <span style={{ opacity: 0.5 }}>.</span>
          </h1>

          {/* Contextualização */}
          <p style={{
            margin: '0 auto var(--space-6)',
            fontSize: 'clamp(16px, 2vw, 20px)',
            color: 'var(--text-muted)',
            maxWidth: 600,
            lineHeight: 1.55,
            fontWeight: 300,
            textWrap: 'pretty',
          }}>
            {priorities.length === 0
              ? 'Agenda livre hoje. Dia raro · use pra adiantar a semana ou tirar o pé.'
              : myLate.length > 0
              ? `Você tem ${myLate.length === 1 ? '1 tarefa atrasada' : `${myLate.length} tarefas atrasadas`} esperando. Vamos começar por elas?`
              : `${myToday.length === 1 ? '1 tarefa' : `${myToday.length} tarefas`} pra hoje. Ritmo bom · dá pra fazer com calma.`
            }
          </p>

          {/* VERSO em destaque */}
          <div style={{
            margin: '0 auto var(--space-6)',
            maxWidth: 640,
            padding: 'var(--space-5) var(--space-6)',
            background: 'rgba(255,255,255,0.55)',
            backdropFilter: 'blur(20px) saturate(120%)',
            WebkitBackdropFilter: 'blur(20px) saturate(120%)',
            border: '1px solid rgba(154,155,229,0.30)',
            borderRadius: 'var(--r-card-lg)',
            boxShadow: '0 24px 64px rgba(154,155,229,0.18)',
            position: 'relative',
          }}>
            <span style={{
              position: 'absolute', top: -16, left: 24,
              padding: '4px 12px',
              background: 'var(--accent)', color: '#fff',
              fontSize: 10, fontWeight: 500, letterSpacing: '0.10em', textTransform: 'uppercase',
              borderRadius: 999,
              boxShadow: '0 4px 12px rgba(154,155,229,0.30)',
            }}>
              ✦ Verso de hoje
            </span>
            <p style={{
              margin: '0 0 12px',
              fontSize: 'clamp(20px, 2.4vw, 28px)',
              lineHeight: 1.4,
              color: 'var(--text)',
              fontWeight: 300,
              letterSpacing: '-0.01em',
              fontStyle: 'italic',
              textWrap: 'pretty',
            }}>
              "{verse.text}"
            </p>
            <div style={{
              fontSize: 13,
              color: 'var(--accent)',
              fontWeight: 500,
              letterSpacing: '0.06em',
              textAlign: 'right',
            }}>
              — {verse.ref}
            </div>
          </div>

          {/* CTA sutil de entrada */}
          <button onClick={onGoToPauta} style={{
            appearance: 'none', border: '1px solid var(--accent)',
            background: 'linear-gradient(135deg, var(--accent), var(--beza-deep))',
            color: '#fff',
            padding: '14px 32px', borderRadius: 'var(--r-pill)',
            fontSize: 15, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
            boxShadow: '0 12px 32px rgba(154,155,229,0.30)',
            display: 'inline-flex', alignItems: 'center', gap: 10,
            transition: 'all var(--t-base)',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 20px 48px rgba(154,155,229,0.42)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = '0 12px 32px rgba(154,155,229,0.30)'; }}
          >
            Começar o dia <Icon.Arrow width={16} height={16} />
          </button>
        </div>
      </section>

      {/* MOOD · linha clean abaixo do hero */}
      <div style={{
        maxWidth: 880, margin: 'var(--space-6) auto 0',
      }}>
        <div style={{
          padding: 'var(--space-5)',
          background: 'var(--surface)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-card-lg)',
          marginBottom: 'var(--space-4)',
        }}>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 14 }}>
            como você está agora
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {MOODS.map(m => {
              const active = currentMood === m.id;
              return (
                <button key={m.id} onClick={() => setMood(m.id)} style={{
                  appearance: 'none', border: '1px solid',
                  borderColor: active ? m.color : 'var(--border)',
                  background: active ? m.color + '15' : 'transparent',
                  color: active ? m.color : 'var(--text-muted)',
                  padding: '10px 16px', borderRadius: 'var(--r-pill)',
                  fontSize: 13, fontFamily: 'inherit', cursor: 'pointer',
                  fontWeight: active ? 500 : 400,
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  transition: 'all var(--t-fast)',
                }}>
                  <span style={{ fontSize: 16 }}>{m.emoji}</span>
                  {m.label}
                </button>
              );
            })}
          </div>
          {currentMood && (
            <p style={{ margin: '12px 0 0', fontSize: 12, color: 'var(--text-faint)', fontStyle: 'italic' }}>
              ✓ registrado · o time pode ver seu status na Pauta
            </p>
          )}
        </div>

        {/* PRIORIDADES · compactas */}
        {priorities.length > 0 && (
          <div style={{
            padding: 'var(--space-5)',
            background: 'var(--surface)',
            border: '1px solid var(--border)',
            borderRadius: 'var(--r-card-lg)',
            marginBottom: 'var(--space-4)',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
              <div className="t-overline" style={{ color: 'var(--accent)' }}>foco do dia</div>
              <button onClick={onGoToPauta} style={{
                appearance: 'none', border: 'none', background: 'transparent',
                color: 'var(--accent)', fontSize: 12, fontFamily: 'inherit', fontWeight: 500,
                cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4,
              }}>ver tudo →</button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {priorities.map((t, idx) => {
                const isLate = t.status === 'atrasada';
                return (
                  <div key={t.id} style={{
                    padding: '10px 14px',
                    background: isLate ? 'rgba(243,77,77,0.06)' : 'var(--surface-soft)',
                    border: '1px solid',
                    borderColor: isLate ? 'rgba(243,77,77,0.30)' : 'var(--border)',
                    borderLeft: `3px solid ${t.typeColor}`,
                    borderRadius: 'var(--r-btn)',
                    display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: 12, alignItems: 'center',
                  }}>
                    <span style={{
                      width: 20, height: 20, borderRadius: '50%',
                      background: isLate ? 'var(--error)' : 'var(--accent)',
                      color: '#fff',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 10, fontWeight: 600,
                    }}>{idx + 1}</span>
                    <div>
                      <div style={{ fontSize: 10, color: t.typeColor, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                        {t.typeLabel} · {t.clientBrand}
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', marginTop: 1 }}>
                        {t.title}
                      </div>
                    </div>
                    <span style={{ fontSize: 11, color: isLate ? 'var(--error)' : 'var(--text-faint)', fontWeight: isLate ? 500 : 400 }}>
                      {isLate ? `⚠ atrasada` : t.dueDay === today ? 'hoje' : `+${t.dueDay - today}d`}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* INTENÇÃO */}
        <div style={{
          padding: 'var(--space-5)',
          background: 'var(--surface)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-card-lg)',
        }}>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 8 }}>
            ✎ intenção do dia
          </div>
          <textarea
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="O que você quer entregar/aprender/concluir hoje?"
            rows={2}
            style={{
              width: '100%', appearance: 'none',
              border: '1px solid var(--border-strong)',
              background: 'var(--bg-flat)', color: 'var(--text)',
              padding: '12px 14px', borderRadius: 'var(--r-btn)',
              fontFamily: 'inherit', fontSize: 14, lineHeight: 1.5,
              outline: 'none', resize: 'vertical', minHeight: 56,
            }}
          />
          <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 11, color: 'var(--text-faint)', fontStyle: 'italic' }}>
              Vai pras suas notas pessoais · só você vê
            </span>
            <button onClick={saveQuickNote} disabled={!draft.trim()} style={{
              appearance: 'none', border: '1px solid',
              borderColor: savedNote ? 'var(--success)' : (draft.trim() ? 'var(--accent)' : 'var(--border)'),
              background: savedNote ? 'rgba(111,200,120,0.10)' : (draft.trim() ? 'var(--accent)' : 'transparent'),
              color: savedNote ? 'var(--success)' : (draft.trim() ? '#fff' : 'var(--text-faint)'),
              padding: '8px 16px', borderRadius: 'var(--r-btn)',
              fontSize: 12, fontWeight: 500, fontFamily: 'inherit',
              cursor: draft.trim() ? 'pointer' : 'not-allowed',
            }}>
              {savedNote ? '✓ salvo' : 'salvar'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function dateLabel() {
  const d = new Date();
  const days = ['domingo','segunda','terça','quarta','quinta','sexta','sábado'];
  const months = ['janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro'];
  return `${days[d.getDay()]}, ${d.getDate()} de ${months[d.getMonth()]}`;
}

Object.assign(window, { MorningView });
