const { ZONES, buildWorkoutProfile, findSegmentAtTime, formatTime, getWorkoutTotalDuration, getZoneDurations } = window.PowerZone;

window.PowerZone = window.PowerZone || {};

window.PowerZone.WorkoutProfile = ({
  segments = [],
  totalDuration,
  elapsedSeconds = 0,
  activeIndex,
  onSeek,
  compact = false,
}) => {
  const safeTotal = getWorkoutTotalDuration(segments, totalDuration);
  const safeElapsed = Math.min(Math.max(0, Number(elapsedSeconds) || 0), safeTotal);
  const profile = buildWorkoutProfile(segments, safeTotal, safeElapsed);
  const resolvedActiveIndex = Number.isInteger(activeIndex)
    ? activeIndex
    : findSegmentAtTime(segments, safeElapsed, safeTotal).index;
  const progressPercent = safeTotal > 0 ? (safeElapsed / safeTotal) * 100 : 0;
  const activeSegment = segments[resolvedActiveIndex];
  const activeColor = ZONES[activeSegment?.zone]?.color || '#A8DA15';
  const isInteractive = typeof onSeek === 'function' && safeTotal > 0;

  return (
    <section
      className={`pz-workout-profile ${compact ? 'pz-workout-profile--compact' : ''}`}
      aria-label="Workout elevation profile"
      style={{ '--pz-profile-accent': activeColor }}
    >
      <div className="pz-profile-chart-shell">
        {!compact && (
          <div className="pz-profile-zone-axis" aria-hidden="true">
            <span className="pz-profile-axis-title">Zone</span>
            {[7, 6, 5, 4, 3, 2, 1].map((zone) => (
              <span key={zone} style={{ color: ZONES[zone]?.color }}>{zone}</span>
            ))}
          </div>
        )}

        <div className="pz-profile-plot">
          <div className="pz-profile-grid" aria-hidden="true">
            {[7, 6, 5, 4, 3, 2, 1].map((zone) => (
              <span key={zone} />
            ))}
          </div>

          <div className="pz-profile-bars" aria-hidden="true">
            {profile.map((segment) => {
              const zoneColor = ZONES[segment.zone]?.color || '#888888';
              return (
                <div
                  key={`${segment.index}-${segment.start}`}
                  className={`pz-profile-segment pz-profile-segment--${segment.status}`}
                  style={{
                    left: `${segment.startPercent}%`,
                    width: `${segment.widthPercent}%`,
                    height: `${segment.heightPercent}%`,
                    '--pz-segment-color': zoneColor,
                  }}
                >
                  <span
                    className="pz-profile-segment-complete"
                    style={{ width: `${segment.completionPercent}%` }}
                  />
                </div>
              );
            })}
          </div>

          <div
            className="pz-profile-playhead"
            style={{ left: `${progressPercent}%` }}
            aria-hidden="true"
          >
            {!compact && <span className="pz-profile-playhead-label">{Math.round(progressPercent)}%</span>}
            <span className="pz-profile-playhead-caret" />
            <span className="pz-profile-playhead-line" />
            <span
              className="pz-profile-playhead-dot"
              style={{
                top: 'auto',
                bottom: `${((Math.min(7, Math.max(1, Number(activeSegment?.zone) || 1))) / 7) * 85}%`,
              }}
            />
          </div>

          {isInteractive && (
            <input
              className="pz-profile-range"
              type="range"
              min="0"
              max={Math.max(1, Math.round(safeTotal))}
              step="1"
              value={Math.round(safeElapsed)}
              onChange={(event) => onSeek(Number(event.target.value))}
              aria-label="Seek workout"
              aria-valuetext={`${formatTime(Math.floor(safeElapsed))} elapsed of ${formatTime(Math.floor(safeTotal))}, Zone ${activeSegment?.zone || 1}`}
            />
          )}
        </div>
      </div>

      {!compact && (
        <div className="pz-profile-labels" aria-hidden="true">
          <span className="pz-profile-label-spacer" />
          <div className="pz-profile-label-track">
            {profile.map((segment) => (
              <div
                key={`${segment.index}-label`}
                className={segment.index === resolvedActiveIndex ? 'is-active' : ''}
                style={{
                  left: `${segment.startPercent}%`,
                  width: `${segment.widthPercent}%`,
                  '--pz-segment-color': ZONES[segment.zone]?.color || '#888888',
                }}
                title={`${segment.label || `Zone ${segment.zone}`} — ${formatTime(segment.duration)}`}
              >
                <strong>{segment.index + 1}</strong>
                <span>{formatTime(segment.duration)}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="pz-profile-progress" aria-hidden="true">
        {profile.map((segment) => {
          const zoneColor = ZONES[segment.zone]?.color || '#888888';
          return (
            <span
              key={`${segment.index}-progress`}
              style={{
                width: `${segment.widthPercent}%`,
                '--pz-segment-color': zoneColor,
              }}
            >
              <i style={{ width: `${segment.completionPercent}%` }} />
            </span>
          );
        })}
        <b style={{ left: `${progressPercent}%` }} />
      </div>
    </section>
  );
};

window.PowerZone.ZoneMixPanel = ({ segments = [], activeZone, title = 'Time in zone' }) => {
  const { byZone, total } = getZoneDurations(segments);
  const mix = [1, 2, 3, 4, 5, 6, 7].map((zone) => ({
    zone,
    seconds: byZone[zone],
    percent: total > 0 ? (byZone[zone] / total) * 100 : 0,
    color: ZONES[zone]?.color || '#888888',
  }));

  return (
    <div className="pz-zone-mix" aria-label={title}>
      <p className="pz-wide-kicker">{title}</p>
      <div className="pz-zone-mix-rows">
        {mix.map((row) => (
          <div
            key={row.zone}
            className={`pz-zone-mix-row${row.zone === activeZone ? ' is-active' : ''}${row.seconds === 0 ? ' is-empty' : ''}`}
            style={{ '--pz-mix-color': row.color }}
          >
            <span className="pz-zone-mix-num">{row.zone}</span>
            <div className="pz-zone-mix-track" aria-hidden="true">
              <i style={{ width: `${Math.max(row.percent, row.seconds > 0 ? 4 : 0)}%` }} />
            </div>
            <span className="pz-zone-mix-time">{formatTime(row.seconds)}</span>
          </div>
        ))}
      </div>
    </div>
  );
};
