// ==========================================================================
// LandingHome — Liquid Glass zero-state.
//
// Renders when a thread has 0 messages AND the canvas is hidden.
// Voice: a translucent studio panel floating over the iridescent stage.
// Greeting period word ("night", "morning") picks up the iris gradient as
// a wow-moment. Composer + starter tiles are glass surfaces with shimmer.
// ==========================================================================

function LandingHome() {
  const { me, threads, sendMessage, uploadFiles, currentThread, route, navigate, streaming } = useStore();
  const [value, setValue] = React.useState('');
  const fileInputRef = React.useRef(null);
  const disabled = !route.threadId || streaming.active;

  const hour = new Date().getHours();
  const period = hour < 5 ? 'night' : hour < 12 ? 'morning' : hour < 17 ? 'afternoon' : hour < 22 ? 'evening' : 'night';
  const firstName = (me && me.name) ? me.name.split(' ')[0] : 'there';

  const send = () => {
    const v = value.trim();
    if (!v) return;
    setValue('');
    sendMessage(v);
  };
  const onFiles = (files) => {
    const arr = Array.from(files);
    if (arr.length) uploadFiles(arr);
  };

  const starters = [
    { kicker: 'Brame',           label: 'Dry January push',     prompt: 'Launch a Dry January push for BRAME. 3 concepts, Meta + TikTok, approved claims only.' },
    { kicker: 'Craft Heritage',  label: 'Post-launch readout',  prompt: 'Readout of last month’s Craft Heritage launch. Which creatives won, which fatigued, what to double down on.' },
    { kicker: 'Q2 panel',        label: 'Refresh',              prompt: 'Refresh the consumer panel for Q2 — tilt toward occasion-led drinkers, keep the current skews.' },
    { kicker: 'LinkedIn',        label: 'Creator brief',        prompt: 'Write a 1-page creator brief for a LinkedIn-native founder story for BRAME.' },
    { kicker: 'Low-cal RTD',     label: 'Naming sprint',        prompt: 'Run a naming sprint for a low-calorie RTD. 15 candidates, 3 territories, availability checked.' },
  ];

  const recentThreads = (threads || []).filter(t => t.id !== currentThread.id).slice(0, 6);
  const brands = [
    { id: 'b_brame',   name: 'BRAME',          kicker: 'Botanical aperitif · 3 SKU' },
    { id: 'b_craft',   name: 'Craft Heritage', kicker: 'Aged spirits · Q3 launch' },
    { id: 'b_loop',    name: 'Loop Foods',     kicker: 'Plant-forward · house brand' },
    { id: 'b_veldt',   name: 'Veldt',          kicker: 'Single-origin · on-trade' },
  ];

  const subline =
    period === 'morning'   ? 'What are we launching today?'
  : period === 'afternoon' ? 'Pick up where you left off — or start something new.'
  : period === 'evening'   ? 'A quiet hour for the big thinking.'
  :                          'Burning the late shift — what are we cracking?';

  const today = new Date();
  const folio = `Vol. ${String(today.getFullYear()).slice(-2)}.${String(today.getMonth() + 1).padStart(2, '0')} · No. ${String(today.getDate()).padStart(2, '0')}`;
  const dateLine = today.toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric' });

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, overflowY: 'auto', position: 'relative' }}>

      {/* ── Folio bar ─────────────────────────────────────────────────── */}
      <div style={{
        maxWidth: 1080, width: '100%', margin: '0 auto', padding: '24px 32px 0',
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      }}>
        <div className="kicker">{folio}</div>
        <div className="kicker">{dateLine}</div>
      </div>

      <div style={{ flex: '0 0 auto', height: 56 }} />

      {/* ── Hero: greeting + glass composer + starter tiles ──────────── */}
      <div className="fade-up" style={{
        position: 'relative', zIndex: 1,
        maxWidth: 920, width: '100%',
        margin: '0 auto', padding: '0 32px',
        display: 'flex', flexDirection: 'column', gap: 36,
      }}>
        <div>
          <div className="display" style={{
            fontSize: 92, color: 'var(--ink)', lineHeight: 1.0,
          }}>
            Good <span className="iridescent" style={{ fontStyle: 'italic', fontWeight: 400 }}>{period}</span>, {firstName}.
          </div>
          <div className="display-italic" style={{
            fontSize: 26, color: 'var(--ink-soft)', marginTop: 14, lineHeight: 1.25,
            maxWidth: 640,
          }}>{subline}</div>
        </div>

        {/* Composer — glass desk, iridescent send pill */}
        <input ref={fileInputRef} type="file" multiple style={{ display: 'none' }}
          accept=".pdf,.csv,.xlsx,.doc,.docx,.png,.jpg,.jpeg"
          onChange={(e) => { onFiles(e.target.files); e.target.value = ''; }} />
        <div
          onDragOver={(e) => { e.preventDefault(); }}
          onDrop={(e) => { e.preventDefault(); onFiles(e.dataTransfer.files); }}
          className="glass-strong"
          style={{
            width: '100%',
            borderRadius: 'var(--radius-lg)',
            padding: '20px 24px 18px',
            display: 'flex', flexDirection: 'column', gap: 12,
          }}>
          <div className="kicker" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>Brief desk</span>
            <span className="iridescent" style={{ fontWeight: 500 }}>Open</span>
          </div>
          <textarea
            value={value}
            onChange={e => setValue(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
            placeholder={disabled && streaming.active ? 'Inku is thinking…' : 'Drop a brief, a deck, or a CSV — or tell me what you’re working on.'}
            disabled={disabled}
            rows={1}
            style={{
              border: 'none', outline: 'none', resize: 'none',
              background: 'transparent',
              fontFamily: 'var(--font-serif)', fontStyle: 'italic',
              fontSize: 20, color: 'var(--ink)',
              minHeight: 36, lineHeight: 1.45, width: '100%',
              padding: '2px 0',
            }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 8, borderTop: '1px solid rgba(255,255,255,0.4)' }}>
            <button className="btn-reset" title="Attach files" disabled={disabled}
              onClick={() => fileInputRef.current?.click()}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '6px 0', color: 'var(--ink-mute)',
                fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.18em',
                textTransform: 'uppercase', cursor: disabled ? 'default' : 'pointer',
              }}>
              <Icon name="upload" size={13} stroke={1.5} />
              Attach
            </button>
            <button className="btn-reset shimmer" onClick={send} disabled={disabled || !value.trim()}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 10,
                padding: '10px 20px', borderRadius: 99,
                background: value.trim() && !disabled ? 'var(--iris)' : 'rgba(255,255,255,0.4)',
                color: value.trim() && !disabled ? '#fff' : 'var(--ink-mute)',
                fontFamily: 'var(--font-serif)', fontStyle: 'italic',
                fontSize: 15, fontWeight: 500, letterSpacing: '-0.005em',
                cursor: value.trim() && !disabled ? 'pointer' : 'default',
                boxShadow: value.trim() && !disabled ? '0 8px 24px rgba(53,2,246,.30), inset 0 1px 0 rgba(255,255,255,0.4)' : 'none',
                transition: 'all .35s var(--ease-fluid)',
              }}>
              Send to studio
              <span style={{ fontFamily: 'var(--font-mono)', fontStyle: 'normal' }}>→</span>
            </button>
          </div>
        </div>

        {/* Starting points — glass tiles with iridescent hover */}
        <div>
          <div className="kicker" style={{ marginBottom: 14 }}>Starting points</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {starters.map((s, i) => (
              <LandingStarter key={s.label} index={i + 1} kicker={s.kicker} label={s.label} onClick={() => sendMessage(s.prompt)} />
            ))}
          </div>
        </div>
      </div>

      {/* ── Lower zone: Lately + Brands as glass columns ────────────── */}
      <div className="fade-in" style={{
        position: 'relative', zIndex: 1,
        marginTop: 64, paddingBottom: 64,
      }}>
        <div style={{ maxWidth: 920, margin: '0 auto', padding: '0 32px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
            <CatalogueColumn
              kicker="Lately"
              count={recentThreads.length}
              empty="No other threads. This is page № 1."
              items={recentThreads.map(t => ({
                id: t.id,
                title: t.title,
                meta: relTimeLanding(t.updatedAt) + (t.messageCount ? ` · ${t.messageCount} msg` : ''),
                onOpen: () => navigate(`/t/${t.id}`),
              }))}
            />
            <CatalogueColumn
              kicker="Brands"
              count={brands.length}
              items={brands.map(b => ({
                id: b.id,
                title: b.name,
                meta: b.kicker,
                onOpen: () => sendMessage(`What's going on with ${b.name} right now?`),
              }))}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Liquid-glass primitives
// ──────────────────────────────────────────────────────────────────────

function relTimeLanding(ts) {
  if (!ts) return 'just now';
  const diff = Date.now() - ts;
  const h = Math.round(diff / 3600000);
  if (h < 1) return 'just now';
  if (h < 24) return `${h}h ago`;
  return `${Math.round(h / 24)}d ago`;
}

function LandingStarter({ index, kicker, label, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button className="btn-reset shimmer" onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        textAlign: 'left',
        padding: '16px 22px',
        borderRadius: 'var(--radius)',
        background: 'var(--glass)',
        WebkitBackdropFilter: 'blur(24px) saturate(180%)',
        backdropFilter: 'blur(24px) saturate(180%)',
        border: '1px solid var(--glass-border)',
        boxShadow: hover ? 'var(--shadow-md), inset 0 1px 0 rgba(255,255,255,.85)' : 'var(--shadow-glass)',
        display: 'grid',
        gridTemplateColumns: '36px 140px 1fr 28px',
        gap: 18, alignItems: 'center',
        cursor: 'pointer',
        transform: hover ? 'translateY(-1px)' : 'none',
        transition: 'transform .35s var(--ease-fluid), box-shadow .35s var(--ease-fluid), border-color .35s var(--ease-fluid)',
        borderColor: hover ? 'var(--glass-border-strong)' : 'var(--glass-border)',
      }}>
      <span className="numeral" style={{ fontSize: 11, color: hover ? 'var(--moss-deep)' : 'var(--ink-mute)' }}>
        {String(index).padStart(2, '0')}
      </span>
      <span className="kicker">{kicker}</span>
      <span style={{
        fontFamily: 'var(--font-serif)',
        fontStyle: hover ? 'italic' : 'normal',
        fontSize: 19, color: 'var(--ink)',
        letterSpacing: '-0.005em',
        transition: 'font-style .15s',
      }}>{label}</span>
      <span className={hover ? 'iridescent' : ''} style={{
        color: hover ? undefined : 'var(--ink-mute)',
        fontFamily: 'var(--font-mono)', fontSize: 16, justifySelf: 'end',
      }}>→</span>
    </button>
  );
}

function CatalogueColumn({ kicker, count, items, empty }) {
  return (
    <div className="glass-card" style={{
      borderRadius: 'var(--radius-lg)',
      padding: '22px 24px 8px',
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
        <span className="kicker">{kicker}</span>
        {typeof count === 'number' && (
          <span className="numeral" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>
            {String(count).padStart(2, '0')}
          </span>
        )}
      </div>
      <hr className="iris-rule" />
      <div style={{ paddingBottom: 6 }}>
        {items.length === 0 && (
          <div className="serif-italic" style={{ padding: '16px 0 22px', color: 'var(--ink-mute)', fontSize: 15 }}>
            {empty || 'Nothing yet.'}
          </div>
        )}
        {items.map((it, i) => (
          <CatalogueRow key={it.id} index={i + 1} title={it.title} meta={it.meta} onOpen={it.onOpen} isLast={i === items.length - 1} />
        ))}
      </div>
    </div>
  );
}

function CatalogueRow({ index, title, meta, onOpen, isLast }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button className="btn-reset" onClick={onOpen}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        width: '100%', textAlign: 'left',
        padding: '14px 0',
        borderBottom: isLast ? 'none' : '1px solid rgba(255,255,255,0.4)',
        display: 'grid', gridTemplateColumns: '28px 1fr auto',
        gap: 12, alignItems: 'baseline',
        cursor: 'pointer',
        color: 'var(--ink)',
      }}>
      <span className="numeral" style={{ fontSize: 10, color: hover ? 'var(--moss-deep)' : 'var(--ink-mute)' }}>
        {String(index).padStart(2, '0')}
      </span>
      <span style={{
        fontFamily: 'var(--font-serif)', fontSize: 17,
        fontStyle: hover ? 'italic' : 'normal',
        letterSpacing: '-0.005em', lineHeight: 1.3,
        transition: 'font-style .15s',
      }}>{title}</span>
      <span className="kicker" style={{ color: hover ? 'var(--moss-deep)' : 'var(--ink-mute)', whiteSpace: 'nowrap', transition: 'color .15s' }}>{meta}</span>
    </button>
  );
}

Object.assign(window, { LandingHome });
