// home.jsx — HomePage
// t, useState, useEffect etc. available from components.jsx (loaded first)

function HomePage({ data, setRoute, onOpenDestiny }) {
  const seed = data || DOPO.SEED;
  const { user, services, assets, memories, people } = seed;

  const totalItems = services.length + assets.length;
  const assignedItems = services.filter(s => s.destiny && s.destiny !== null).length
    + assets.filter(a => a.destiny && a.destiny !== null).length;
  const memoriesCount = memories.length;
  const circleCount = people.length;

  const unassignedServices = services.filter(s => !s.destiny).slice(0, 3);
  const latestMemories = memories.slice(0, 4);
  const latestServices = services.slice(0, 5);

  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'Buongiorno' : hour < 18 ? 'Buon pomeriggio' : 'Buonasera';

  const suggestions = [
    {
      icon: 'shield',
      color: 'var(--olive-500)',
      title: 'Completa l\'inventario',
      desc: `${totalItems - assignedItems} servizi senza destino. Decidili ora.`,
      action: () => setRoute('inventory'),
    },
    {
      icon: 'memories',
      color: 'var(--jade-700)',
      title: 'Scrivi una memoria',
      desc: 'Una lettera, un audio, una foto. Per chi ami.',
      action: () => setRoute('memories'),
    },
    {
      icon: 'circle',
      color: 'var(--gr-700)',
      title: 'Invita la cerchia',
      desc: `${people.filter(p => !p.invited).length} persone non ancora invitate.`,
      action: () => setRoute('circle'),
    },
  ];

  const kindLabel = { letter: 'Lettera', audio: 'Audio', photo: 'Foto', video: 'Video', doc: 'Documento' };
  const kindClass = { letter: 'mem-letter', audio: 'mem-audio', photo: 'mem-photo', video: 'mem-video', doc: 'mem-doc' };

  return (
    <div className="fade-in">
      {/* Hero */}
      <div className="home-hero">
        {/* Left */}
        <div>
          <div className="t-eyebrow" style={{ marginBottom: 12 }}>
            {greeting}, {user.name.split(' ')[0]}
          </div>
          <h1
            className="hero-display t-display"
            style={{ fontSize: 68, fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontWeight: 400, color: 'var(--ink)', margin: '0 0 16px', lineHeight: 1.0 }}
          >
            {t.home.hero_title_serif}
            <br />
            <span style={{ color: 'var(--accent-ink)' }}>{t.home.hero_title_serif_2}</span>
          </h1>
          <p className="hero-sub">{t.home.hero_sub}</p>
          <div className="row" style={{ flexWrap: 'wrap', gap: 10 }}>
            <button className="btn btn-primary" onClick={() => setRoute('inventory')}>
              <Icon name="inventory" size={15} color="#fff" />
              Vai all'inventario
            </button>
            <button className="btn btn-secondary" onClick={() => setRoute('memories')}>
              <Icon name="plus" size={15} />
              {t.home.add_memory}
            </button>
          </div>
        </div>

        {/* Right — progress card */}
        <div>
          <div className="card" style={{ overflow: 'hidden' }}>
            {/* Header */}
            <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid var(--line)' }}>
              <div className="row" style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', flex: 1 }}>
                  {t.home.plan_title}
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-muted)' }}>
                  {seed.profileProgress}% {t.home.plan_complete}
                </div>
              </div>
              <div className="progress">
                <div style={{ width: `${seed.profileProgress}%` }} />
              </div>
            </div>

            {/* Stats */}
            <div className="stats-grid">
              <StatCell num={assignedItems} label="Assegnati" accent />
              <StatCell num={memoriesCount} label="Memorie" />
              <StatCell num={circleCount} label="Persone" />
            </div>

            {/* Circle */}
            <div style={{ padding: '16px 24px' }}>
              <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginBottom: 10 }}>
                {t.home.your_circle}
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {people.map(p => (
                  <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <Monogram initials={p.initials} color={p.color} size="sm" />
                    <span style={{ fontSize: 12, color: 'var(--ink-muted)' }}>{p.name.split(' ')[0]}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Unassigned alert */}
          {unassignedServices.length > 0 && (
            <div style={{
              marginTop: 12,
              padding: '14px 16px',
              background: 'var(--yel-100)',
              border: '1px solid #EDB526',
              borderRadius: 12,
              display: 'flex',
              gap: 12,
              alignItems: 'flex-start',
            }}>
              <Icon name="alert" size={16} color="var(--yel-700)" style={{ flexShrink: 0 }} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--yel-700)', marginBottom: 4 }}>
                  {unassignedServices.length + services.filter(s => !s.destiny).length - unassignedServices.length} servizi senza destino
                </div>
                <div style={{ fontSize: 12, color: 'var(--yel-700)', opacity: 0.8 }}>
                  Decidi cosa succederà a Google Drive, Fineco e altri.
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Suggestions */}
      <div style={{ marginBottom: 40 }}>
        <SectionHeader
          title={t.home.suggestions}
          action={
            <button className="btn btn-ghost btn-sm" onClick={() => setRoute('inventory')}>
              {t.home.see_all} <Icon name="arrow_right" size={14} />
            </button>
          }
        />
        <div className="suggestions-grid">
          {suggestions.map((s, i) => (
            <div key={i} className="card suggestion-card" onClick={s.action}>
              <div style={{
                width: 40,
                height: 40,
                borderRadius: 10,
                background: s.color + '18',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginBottom: 14,
              }}>
                <Icon name={s.icon} size={20} color={s.color} />
              </div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>
                {s.title}
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-muted)', lineHeight: 1.4 }}>
                {s.desc}
              </div>
              <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 4, fontSize: 12, color: 'var(--accent)', fontWeight: 500 }}>
                Vai <Icon name="arrow_right" size={13} color="var(--accent)" />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Latest memories */}
      <div style={{ marginBottom: 40 }}>
        <SectionHeader
          title={t.home.latest_memories}
          action={
            <button className="btn btn-ghost btn-sm" onClick={() => setRoute('memories')}>
              {t.home.see_all} <Icon name="arrow_right" size={14} />
            </button>
          }
        />
        <div className="mem-grid">
          {latestMemories.map(m => {
            const cls = kindClass[m.kind] || 'mem-doc';
            const kl = kindLabel[m.kind] || m.kind;
            const pMap = Object.fromEntries(seed.people.map(p => [p.id, p]));
            return (
              <div key={m.id} className="mem-card" onClick={() => setRoute('memories')}>
                <div className={`mem-card-cover ${cls}`}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <span className="kind-tag">
                      <Icon name={m.kind === 'doc' ? 'doc' : m.kind === 'letter' ? 'letter' : m.kind === 'audio' ? 'audio' : m.kind === 'video' ? 'video' : 'photo'} size={11} />
                      {kl}
                    </span>
                  </div>
                  {m.kind === 'letter' && (
                    <div style={{
                      position: 'absolute',
                      bottom: 16,
                      left: 16,
                      right: 16,
                      fontFamily: 'var(--f-serif)',
                      fontStyle: 'italic',
                      fontSize: 13,
                      lineHeight: 1.5,
                      color: 'var(--ink)',
                      opacity: 0.7,
                      overflow: 'hidden',
                      display: '-webkit-box',
                      WebkitLineClamp: 4,
                      WebkitBoxOrient: 'vertical',
                    }}>
                      {m.body}
                    </div>
                  )}
                  {m.kind === 'photo' && (
                    <div style={{ position: 'absolute', bottom: 16, left: 16, fontSize: 24, opacity: 0.5 }}>
                      🌊
                    </div>
                  )}
                  {m.kind === 'audio' && (
                    <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16 }}>
                      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', marginBottom: 4 }}>DURATA</div>
                      <div style={{ fontSize: 20, fontFamily: 'var(--f-mono)', color: '#fff', fontWeight: 500 }}>
                        {m.duration}
                      </div>
                    </div>
                  )}
                  {m.kind === 'video' && (
                    <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16 }}>
                      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', marginBottom: 4 }}>VIDEO</div>
                      <div style={{ fontSize: 16, fontFamily: 'var(--f-mono)', color: '#fff', fontWeight: 500 }}>
                        {m.duration}
                      </div>
                    </div>
                  )}
                  {/* Assignees */}
                  {m.assignees.length > 0 && (
                    <div style={{ position: 'absolute', bottom: 16, right: 16 }}>
                      <MonoStack ids={m.assignees} people={seed.people} max={2} />
                    </div>
                  )}
                </div>
                <div className="mem-card-meta">
                  <div className="mem-card-title">{m.title}</div>
                  <div className="mem-card-sub">{new Date(m.date).toLocaleDateString('it-IT', { year: 'numeric', month: 'short', day: 'numeric' })}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Latest services */}
      <div>
        <SectionHeader
          title={t.home.latest_services}
          action={
            <button className="btn btn-ghost btn-sm" onClick={() => setRoute('inventory')}>
              {t.home.see_all} <Icon name="arrow_right" size={14} />
            </button>
          }
        />
        <div className="card" style={{ overflow: 'hidden' }}>
          <table className="tbl latest-services-tbl">
            <thead>
              <tr>
                <th>Servizio</th>
                <th>Categoria</th>
                <th>Destino</th>
                <th>Persone</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {latestServices.map(s => (
                <tr key={s.id} onClick={() => onOpenDestiny(s, 'service')}>
                  <td>
                    <div className="row" style={{ gap: 12 }}>
                      <ServiceBadge icon={s.icon} color={s.color} size={32} />
                      <div>
                        <div style={{ fontWeight: 500, color: 'var(--ink)' }}>{s.name}</div>
                        <div className="t-mono">{s.email}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <span className="chip chip-muted">{s.category}</span>
                  </td>
                  <td>
                    <DestinyPill destiny={s.destiny} />
                  </td>
                  <td>
                    {s.assignees.length > 0 ? (
                      <MonoStack ids={s.assignees} people={seed.people} />
                    ) : (
                      <span style={{ color: 'var(--gr-300)', fontSize: 13 }}>—</span>
                    )}
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <button className="btn btn-ghost btn-sm" onClick={e => { e.stopPropagation(); onOpenDestiny(s, 'service'); }}>
                      <Icon name="edit" size={14} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomePage });
