// HEM-vyn — hero med nästa vattning, dagens lista, väder, statistik, tips.

function PlantDisc({ hue, size = 44 }) {
  const h = TV.HUES[hue] || TV.HUES.herb;
  return (
    <div className="disc" style={{ width: size, height: size, background: h.bg }}>
      <svg width={size * 0.7} height={size * 0.7} viewBox="0 0 24 24">
        <path d="M12 22 V 11" stroke={h.leaf} strokeWidth="1.6" strokeLinecap="round" fill="none"/>
        <path d="M12 12 C 12 8.5, 9.5 6.5, 6 6.5 C 6 10, 8.5 12, 12 12 z" fill={h.accent} stroke={h.leaf} strokeWidth="0.8"/>
        <path d="M12 14 C 12 10.5, 14.5 8.5, 18 8.5 C 18 12, 15.5 14, 12 14 z" fill={h.leaf} stroke={h.leaf} strokeWidth="0.8"/>
        <path d="M8 18 H 16 L 15 22 H 9 z" fill={h.leaf} opacity="0.55"/>
      </svg>
    </div>
  );
}

function WeatherIcon({ name, size = 22, color }) {
  const C = Icon[name] || Icon.Sun;
  return <span style={{ color: color || 'currentColor', display: 'inline-flex' }}><C size={size}/></span>;
}

function HeroNext({ plant, status, zones, onWater, rainTomorrow, busy }) {
  if (!plant) return null;
  const isOverdue = status.kind === 'overdue';
  const isToday = status.kind === 'today';
  const isManual = status.kind === 'manual';

  let bigText, sub;
  if (isOverdue) { bigText = `${status.days} ${status.days === 1 ? 'dag' : 'dagar'} sen`; sub = 'borde vattnats redan'; }
  else if (isToday) { bigText = 'Idag'; sub = 'dags att vattna'; }
  else if (isManual) { bigText = 'Känn på jorden'; sub = `senast vattnad ${TV.formatLast(plant.last)}`; }
  else { bigText = `om ${status.days} ${status.days === 1 ? 'dag' : 'dagar'}`; sub = `nästa vattning`; }

  const zoneName = zones.find(z => z.id === plant.zone)?.name;

  return (
    <div style={{
      background: 'linear-gradient(150deg, var(--primary-deep) 0%, var(--primary) 100%)',
      borderRadius: 'var(--r-card)',
      padding: 'var(--pad-card)',
      color: '#FBF7EA',
      position: 'relative', overflow: 'hidden',
    }}>
      <svg width="170" height="170" viewBox="0 0 170 170" style={{ position: 'absolute', right: -30, top: -30, opacity: 0.13 }}>
        <path d="M90 10 C 40 30, 20 80, 30 130 C 80 120, 130 80, 140 30 C 120 20, 100 14, 90 10 z" fill="#FBF7EA"/>
        <path d="M30 130 C 60 110, 90 80, 120 50" stroke="#FBF7EA" strokeWidth="2" fill="none"/>
      </svg>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, position: 'relative' }}>
        <span className="eyebrow" style={{ color: 'rgba(251,247,234,0.72)' }}>
          {isOverdue ? 'Försenad' : isToday ? 'Nästa vattning' : isManual ? 'Kontrollera' : 'Nästa vattning'}
        </span>
        <span className="pill" style={{ background: 'rgba(251,247,234,0.14)', color: 'rgba(251,247,234,0.92)' }}>
          <Icon.Drop size={11}/> {zoneName}
        </span>
      </div>

      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, position: 'relative' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="serif" style={{ fontSize: 36, lineHeight: 1.05, letterSpacing: '-0.02em', marginBottom: 4 }}>
            {bigText}
          </div>
          <div style={{ fontSize: 14.5, color: 'rgba(251,247,234,0.78)', marginBottom: 10 }}>
            {plant.name} · {sub}
          </div>
        </div>
        <PlantDisc hue={plant.hue} size={56}/>
      </div>

      {rainTomorrow && (isToday || isOverdue) && (
        <div style={{
          marginTop: 14, padding: '10px 12px',
          background: 'rgba(251,247,234,0.13)',
          borderRadius: 12, fontSize: 13,
          display: 'flex', alignItems: 'center', gap: 9,
        }}>
          <span style={{ color: 'rgba(251,247,234,0.95)' }}><Icon.CloudRain size={18}/></span>
          <div style={{ flex: 1 }}>
            <strong style={{ fontWeight: 600 }}>Regn imorgon ({rainTomorrow.rain} mm)</strong>
            <div style={{ color: 'rgba(251,247,234,0.7)', fontSize: 12.5 }}>Du kan kanske skippa altan & rabatt idag.</div>
          </div>
        </div>
      )}

      <button
        disabled={busy}
        onClick={(e) => onWater(plant.id, e)}
        style={{
          marginTop: 14, width: '100%',
          background: '#FBF7EA', color: 'var(--primary-deep)',
          border: 0, height: 48, borderRadius: 14,
          font: '600 15.5px/1 Geist, system-ui, sans-serif',
          letterSpacing: '-0.005em',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          cursor: busy ? 'progress' : 'pointer',
          boxShadow: '0 2px 0 rgba(0,0,0,0.04)',
          opacity: busy ? 0.7 : 1,
        }}>
        <Icon.Drop size={17}/> Vattnat {plant.name}
      </button>
    </div>
  );
}

function TodayList({ plants, onWater, onOpen }) {
  if (plants.length === 0) {
    return (
      <div className="card leaf-stamp" style={{ padding: 'var(--pad-card)', textAlign: 'center' }}>
        <div style={{ fontSize: 38, marginBottom: 4 }}>🌿</div>
        <div className="serif" style={{ fontSize: 19 }}>Allt är vattnat idag!</div>
        <div style={{ fontSize: 13.5, color: 'var(--ink-muted)', marginTop: 4 }}>
          Sätt dig ner med en kopp kaffe — växterna mår bra.
        </div>
      </div>
    );
  }
  return (
    <div className="card" style={{ padding: 6, paddingTop: 6 }}>
      {plants.map((p, i) => {
        const st = TV.statusOf(p);
        const isOverdue = st.kind === 'overdue';
        return (
          <div key={p.id} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '10px 12px',
            borderBottom: i < plants.length - 1 ? '1px solid var(--line)' : 'none',
          }}>
            <button onClick={() => onOpen(p.id)} style={{
              background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 12, flex: 1, minWidth: 0, textAlign: 'left',
            }}>
              <PlantDisc hue={p.hue} size={38}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {p.name}
                </div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-subtle)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
                  {isOverdue ? (
                    <span style={{ color: 'var(--warn)', fontWeight: 500 }}>{st.days} {st.days===1?'dag':'dagar'} sen</span>
                  ) : (
                    <span>idag</span>
                  )}
                  {p.schedule.type === 'every' && (
                    <>
                      <span style={{ color: 'var(--ink-faint)' }}>·</span>
                      <span>var {p.schedule.days}:e dag</span>
                    </>
                  )}
                </div>
              </div>
            </button>
            <button className="btn-water compact" onClick={(e) => onWater(p.id, e)}>
              <Icon.Drop size={14}/> Vattnat
            </button>
          </div>
        );
      })}
    </div>
  );
}

function WeatherStrip() {
  return (
    <div className="card" style={{ padding: 'var(--pad-card)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <span className="eyebrow">Veckans väder</span>
        <span style={{ fontSize: 12.5, color: 'var(--ink-subtle)' }}>Hamburgsund</span>
      </div>
      <div style={{ display: 'flex', gap: 6 }}>
        {TV.WEATHER.map((w, i) => {
          const wet = w.rain >= 3;
          return (
            <div key={i} style={{
              flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              padding: '8px 2px', borderRadius: 12,
              background: i === 0 ? 'var(--bg-tonal)' : 'transparent',
              border: i === 0 ? '1px solid var(--line)' : '1px solid transparent',
            }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-subtle)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>
                {w.short}
              </div>
              <span style={{ color: wet ? 'var(--rain)' : 'var(--gold)' }}>
                <WeatherIcon name={w.icon} size={20}/>
              </span>
              <div style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--ink)' }} className="numerical">{w.tempH}°</div>
              {wet && (
                <div style={{ fontSize: 9.5, color: 'var(--rain)', fontWeight: 600 }} className="numerical">
                  {w.rain}mm
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function StatsRow({ plants, history }) {
  const total = plants.length;
  const wateredThisWeek = history.filter(h => h.at > Date.now() - 7 * TV.DAY).length;
  // Streak: antalet sammanhängande dagar bakåt med minst en vattning. Räkna fram.
  const streak = computeStreak(history);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
      <StatCell label="Streak" value={streak} unit="dagar" icon={<Icon.Flame/>} tint="var(--accent)"/>
      <StatCell label="Vattnat" value={wateredThisWeek} unit="i veckan" icon={<Icon.Drop size={15}/>} tint="var(--water)"/>
      <StatCell label="Plantor" value={total} unit="totalt" icon={<Icon.Sprout size={16}/>} tint="var(--primary)"/>
    </div>
  );
}

function computeStreak(history) {
  if (!history.length) return 0;
  const days = new Set(history.map(h => new Date(h.at).toDateString()));
  let streak = 0;
  let d = new Date();
  while (days.has(d.toDateString())) {
    streak++;
    d.setDate(d.getDate() - 1);
    if (streak > 365) break;
  }
  return streak;
}

function StatCell({ label, value, unit, icon, tint }) {
  return (
    <div className="card" style={{ padding: '12px 12px 14px' }}>
      <div style={{ color: tint, marginBottom: 6 }}>{icon}</div>
      <div className="serif numerical" style={{ fontSize: 26, lineHeight: 1, letterSpacing: '-0.02em' }}>{value}</div>
      <div style={{ fontSize: 11, color: 'var(--ink-subtle)', marginTop: 4, fontWeight: 500 }}>
        {label}
      </div>
      <div style={{ fontSize: 10.5, color: 'var(--ink-faint)', marginTop: 1 }}>{unit}</div>
    </div>
  );
}

function TipCard({ tip }) {
  return (
    <div className="card" style={{ padding: 'var(--pad-card)', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: 'var(--accent-wash)', color: 'var(--accent)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <Icon.Sparkle size={18}/>
      </div>
      <div style={{ flex: 1 }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>Visste du att</div>
        <div className="serif" style={{ fontSize: 17, lineHeight: 1.25, marginBottom: 4 }}>{tip.title}</div>
        <div style={{ fontSize: 13.5, color: 'var(--ink-muted)', lineHeight: 1.45 }}>{tip.body}</div>
      </div>
    </div>
  );
}

function RainBanner({ weather }) {
  const tomorrow = weather[1];
  if (!tomorrow || tomorrow.rain < 3) return null;
  return (
    <div style={{
      background: 'var(--water-wash)',
      color: 'var(--rain)',
      borderRadius: 'var(--r-card)',
      padding: '14px 16px',
      display: 'flex', alignItems: 'center', gap: 12,
      border: '1px solid color-mix(in srgb, var(--water) 22%, transparent)',
    }}>
      <span style={{ flexShrink: 0 }}><Icon.CloudRain size={26}/></span>
      <div style={{ flex: 1, color: 'var(--ink)' }}>
        <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--rain)' }}>Imorgon väntas regn ({tomorrow.rain} mm)</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-muted)', marginTop: 2 }}>
          Utomhus-plantor klarar sig — vattna bara växthuset idag.
        </div>
      </div>
    </div>
  );
}

function HomeScreen({ plants, zones, history, onWater, onOpen, onGoPlants, busyId, userName }) {
  const sorted = [...plants].filter(p => p.schedule.type !== 'when_dry')
    .sort((a, b) => TV.nextDue(a) - TV.nextDue(b));
  const hero = sorted[0];
  const heroStatus = hero ? TV.statusOf(hero) : null;

  const todays = plants.filter(p => {
    const st = TV.statusOf(p);
    return st.kind === 'today' || st.kind === 'overdue';
  }).sort((a, b) => {
    const sa = TV.statusOf(a), sb = TV.statusOf(b);
    if (sa.kind === 'overdue' && sb.kind !== 'overdue') return -1;
    if (sb.kind === 'overdue' && sa.kind !== 'overdue') return 1;
    return (sb.days || 0) - (sa.days || 0);
  });

  const tip = TV.TIPS[Math.floor(Date.now() / TV.DAY) % TV.TIPS.length];
  const rainTomorrow = TV.WEATHER[1].rain >= 3 ? TV.WEATHER[1] : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap-section)', padding: '0 16px 24px' }}>
      <div style={{ paddingTop: 4 }}>
        <div className="eyebrow" style={{ marginBottom: 6 }}>{TV.todayLabel()}</div>
        <h1 className="serif" style={{ fontSize: 30, lineHeight: 1.05, letterSpacing: '-0.015em' }}>
          {TV.greeting()}{userName ? `, ${userName}` : ''}.
          <span className="serif-italic" style={{ color: 'var(--ink-muted)', display: 'block', fontSize: 22, marginTop: 2 }}>
            {todays.length > 0 ? `${todays.length} ${todays.length === 1 ? 'planta' : 'plantor'} vill ha vatten.` : 'allt är vattnat idag.'}
          </span>
        </h1>
      </div>

      {rainTomorrow && <RainBanner weather={TV.WEATHER}/>}

      <HeroNext plant={hero} status={heroStatus} zones={zones} onWater={onWater}
                rainTomorrow={rainTomorrow} busy={busyId === hero?.id}/>

      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10, padding: '0 4px' }}>
          <h2 className="serif" style={{ fontSize: 20 }}>Behöver vattnas idag</h2>
          {todays.length > 0 && (<span className="pill primary">{todays.length}</span>)}
        </div>
        <TodayList plants={todays} onWater={onWater} onOpen={onOpen}/>
      </div>

      <WeatherStrip/>

      <div>
        <h2 className="serif" style={{ fontSize: 20, marginBottom: 10, padding: '0 4px' }}>Din trädgårds-vecka</h2>
        <StatsRow plants={plants} history={history}/>
      </div>

      <TipCard tip={tip}/>

      <button onClick={onGoPlants} style={{
        appearance: 'none', border: '1px solid var(--line-strong)',
        background: 'transparent', color: 'var(--ink)',
        height: 46, borderRadius: 'var(--r-card)',
        font: '500 14.5px/1 Geist, system-ui, sans-serif',
        cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>
        Visa alla {plants.length} plantor <Icon.ChevronRight size={14}/>
      </button>
    </div>
  );
}

window.PlantDisc = PlantDisc;
window.HomeScreen = HomeScreen;
