// V2FlowStack — Vertical power-flow stack with central spine.
// Replaces the pentagon diagram. Lives inside the hero card's right column.

// ── Flow row data builder ──────────────────────────────────────────────────
function buildFlowRows(s, t) {
  const pvActive = s.pv > 0.05;
  const gridExporting = s.grid < -0.05;
  const gridImporting = s.grid > 0.05;
  const batCharging = s.battery < -0.05;
  const batDischarging = s.battery > 0.05;
  const evCharging = (s.ev || 0) > 0.05;

  return [
    {
      key: 'solar', icon: 'sun',
      label: t('home.flow.solar'),
      sub: pvActive ? t('home.flow.solar.generating') : t('home.flow.solar.night'),
      kw: s.pv, active: pvActive,
      dir: 'right', // source → bus
      color: '#E8C547', tab: 'forecast',
    },
    {
      key: 'grid', icon: 'zap',
      label: t('home.flow.grid'),
      sub: gridExporting ? t('home.flow.grid.export') : t('home.flow.grid.import'),
      kw: Math.abs(s.grid), active: gridImporting || gridExporting,
      dir: gridExporting ? 'left' : 'right', // import=source→bus, export=bus→node
      color: T.textSecondary, tab: null,
    },
    {
      key: 'home', icon: 'home',
      label: t('home.flow.home'),
      sub: t('home.flow.home.usage'),
      kw: s.home, active: s.home > 0.05,
      dir: 'left', // always sink ← bus
      color: T.textPrimary, tab: null,
    },
    {
      key: 'battery', icon: 'battery',
      label: t('home.flow.battery'),
      sub: batCharging ? t('home.flow.battery.charging')
         : batDischarging ? t('home.flow.battery.discharging')
         : '—',
      kw: Math.abs(s.battery),
      active: batCharging || batDischarging,
      dir: batDischarging ? 'right' : 'left',
      color: T.green, tab: 'battery',
      extra: `${s.batterySOC}%`,
    },
    ...(s.ev !== undefined ? [{
      key: 'ev', icon: 'car',
      label: t('home.flow.ev'),
      sub: evCharging ? t('home.flow.car.charging') : t('home.flow.car.ready'),
      kw: s.ev || 0, active: evCharging,
      dir: 'left', // always sink
      color: T.blue, tab: 'car',
    }] : []),
  ];
}

// ── Arrow component ────────────────────────────────────────────────────────
function FlowArrow({ dir, active, tierColor }) {
  // Pill wrapper — subtle tinted bg for active, transparent for idle
  const pillStyle = {
    width: 40, height: 28, borderRadius: 7,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    background: 'transparent',
    border: active ? '1px solid rgba(45, 212, 168, 0.22)' : `1px solid ${T.border}`,
    opacity: active ? 1 : 0.35,
    transition: 'all 0.2s',
  };
  if (!active) {
    return (
      <div style={pillStyle}>
        <div style={{ width: 6, height: 6, borderRadius: '50%', background: T.textMuted }}/>
      </div>
    );
  }
  const isRight = dir === 'right';
  return (
    <div style={pillStyle}>
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={tierColor}
           strokeWidth="2.75" strokeLinecap="round" strokeLinejoin="round"
           style={{ animation: 'flow-pulse-h 2.8s ease-in-out infinite' }}>
        {isRight ? (
          <><line x1="5" y1="12" x2="19" y2="12"/><polyline points="14 7 19 12 14 17"/></>
        ) : (
          <><line x1="19" y1="12" x2="5" y2="12"/><polyline points="10 7 5 12 10 17"/></>
        )}
      </svg>
    </div>
  );
}

// ── Main component ─────────────────────────────────────────────────────────
function V2FlowStack({ s, setCurrent }) {
  const { t } = useLocale();
  const rows = React.useMemo(() => buildFlowRows(s, t), [s, t]);
  const tierColor = TIER_COLOR[s.tier] || T.blue;

  const summaryKey = s.grid < 0 ? 'home.flow.summary.export' : 'home.flow.summary.import';
  const summaryText = t(summaryKey, { kw: Math.abs(s.grid).toFixed(1) });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Header */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        marginBottom: 12,
      }}>
        <span style={{
          fontSize: 9, fontWeight: 700, letterSpacing: 1.2,
          textTransform: 'uppercase', color: T.textMuted,
        }}>{t('home.flow.title')}</span>
        <span
          style={{
            fontSize: 10, color: tierColor, fontFamily: T.fontMono, fontWeight: 600,
            cursor: 'pointer',
          }}
          onClick={() => setCurrent && setCurrent('battery')}
        >{summaryText}</span>
      </div>

      {/* Stack */}
      <div style={{ flex: 1, position: 'relative' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2, position: 'relative' }}>
          {rows.map(row => (
            <div
              key={row.key}
              onClick={row.tab ? () => setCurrent && setCurrent(row.tab) : undefined}
              style={{
                display: 'grid',
                gridTemplateColumns: '36px 40px 1fr 3px 52px',
                alignItems: 'center',
                columnGap: 10,
                padding: '6px 4px',
                borderRadius: 8,
                cursor: row.tab ? 'pointer' : 'default',
                transition: 'background 0.15s',
              }}
              onMouseEnter={e => { if (row.tab) e.currentTarget.style.background = `${T.raised}`; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
            >
              {/* Icon circle */}
              <div style={{
                width: 36, height: 36, borderRadius: '50%',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                border: `1.4px solid ${row.active ? row.color : T.border}`,
                background: row.active ? `${row.color}12` : 'transparent',
                opacity: row.active ? 1 : 0.45,
                transition: 'all 0.2s',
              }}>
                <LI name={row.icon} size={16} color={row.active ? row.color : T.textMuted}/>
              </div>

              {/* Arrow / bullet */}
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <FlowArrow dir={row.dir} active={row.active} tierColor={tierColor}/>
              </div>

              {/* Labels */}
              <div style={{ minWidth: 0 }}>
                <div style={{
                  fontSize: 9, fontWeight: 700, letterSpacing: 1,
                  textTransform: 'uppercase', color: T.textMuted, lineHeight: 1.2,
                }}>{row.label}</div>
                <div style={{
                  fontSize: 10, color: T.textMuted, opacity: 0.6,
                  fontFamily: T.fontMono, marginTop: 1, lineHeight: 1.2,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                }}>{row.sub}</div>
              </div>

              {/* Spine segment */}
              <div style={{
                width: 3, alignSelf: 'stretch', borderRadius: 3,
                background: tierColor, opacity: 0.32,
              }}/>

              {/* kW value */}
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{
                  fontSize: 13, fontWeight: 600, fontFamily: T.fontMono,
                  color: row.active ? T.textPrimary : T.textMuted,
                  lineHeight: 1.2,
                }}>{row.kw.toFixed(1)} <span style={{ fontSize: 10, color: T.textMuted, fontWeight: 400 }}>kW</span></div>
                {row.extra && (
                  <div style={{
                    fontSize: 10, color: T.textMuted, fontFamily: T.fontMono,
                    marginTop: 1, lineHeight: 1.2,
                  }}>{row.extra}</div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { V2FlowStack, buildFlowRows });
