// OverviewSheet.jsx — swipe-up sheets on the Map page
// Two states: 'overview' (list of locations) and 'detail' (single location stats)

const LOCATIONS = [
{ id: 'vardar-n', name: 'Karposh (Vardar Riverside)', sub: 'Industrial waste 2.1 km away', score: 94, trend: 'rising', kind: 'red',
  region: 'Skopje', zone: 'Industrial waste zone', quality: 32, reportsToday: 7,
  forecast: 'Critical in 2 days', confidence: 87,
  aiBody: 'Industrial zone 1.4km upstream. Pattern matches chemical discharge from 06:00 - 08:00. Confidence 87%.' },
{ id: 'centar', name: 'Centar', sub: 'Plastic debris 0.8 km', score: 72, trend: 'stable', kind: 'orange',
  region: 'Skopje', zone: 'Plastic debris zone', quality: 41, reportsToday: 4,
  forecast: 'Medium risk in 2 days', confidence: 62,
  aiBody: 'Tourist zone outflow. Plastic accumulation pattern detected near pier. Confidence 62%.' },
{ id: 'aerodrom', name: 'Aerodrom', sub: 'Agricultural runoff', score: 45, trend: 'improving', kind: 'green',
  region: 'Skopje', zone: 'Monitored area', quality: 68, reportsToday: 1,
  forecast: 'Low risk in 2 days', confidence: 28,
  aiBody: 'No significant anomalies. Slight improvement trend detected. Confidence 28%.' },
{ id: 'ohrid', name: 'Lake Ohrid inlet', sub: 'Plastic debris 0.8 km', score: 87, trend: 'stable', kind: 'orange',
  region: 'Ohrid', zone: 'Plastic debris zone', quality: 41, reportsToday: 4,
  forecast: 'Medium risk in 2 days', confidence: 76,
  aiBody: 'Tourist zone outflow. Plastic accumulation pattern detected near pier. Confidence 76%.' },
{ id: 'dojran', name: 'Dojran Lake', sub: 'monitored stable', score: 61, trend: 'good', kind: 'green',
  region: 'Dojran', zone: 'Monitored area', quality: 72, reportsToday: 0,
  forecast: 'Low risk in 2 days', confidence: 92,
  aiBody: 'No anomalies detected. Sensors report nominal values. Confidence 92%.' }];


const FORECAST_DETAILS = {
  red: {
    prediction: 'Predicted to reach critical pollution levels in 2 days',
    chartPoints: [100, 88, 68, 45, 22],
    chartColor: '#E94B4B',
    reasons: [
      { icon: '🌧️', label: 'Heavy rain\nforecast' },
      { icon: '💧', label: 'High upstream\nwater discharge' },
      { icon: '🏭', label: 'Increased industrial\nactivity' },
    ],
    stats: [
      { label: 'Current risk', value: 'High', color: '#E94B4B' },
      { label: 'Peak in', value: '2 days', color: '#111827' },
      { label: 'Affected area', value: '4.2 km²', color: '#111827' },
      { label: 'Alert level', value: 'Critical', color: '#E94B4B' },
    ],
  },
  orange: {
    prediction: 'Moderate pollution increase expected in 2 days',
    chartPoints: [65, 62, 58, 60, 65],
    chartColor: '#F08537',
    reasons: [
      { icon: '🌦️', label: 'Moderate rain\nexpected' },
      { icon: '🌊', label: 'Seasonal runoff\npatterns' },
      { icon: '🚤', label: 'Increased boat\ntraffic' },
    ],
    stats: [
      { label: 'Current risk', value: 'Medium', color: '#F08537' },
      { label: 'Peak in', value: '2 days', color: '#111827' },
      { label: 'Affected area', value: '2.1 km²', color: '#111827' },
      { label: 'Alert level', value: 'Moderate', color: '#F08537' },
    ],
  },
  green: {
    prediction: 'Conditions stable, low risk expected over next 4 days',
    chartPoints: [100, 98, 96, 97, 100],
    chartColor: '#16A34A',
    reasons: [
      { icon: '☀️', label: 'Clear weather\nforecast' },
      { icon: '📊', label: 'Normal sensor\nreadings' },
      { icon: '✅', label: 'Stable upstream\nconditions' },
    ],
    stats: [
      { label: 'Current risk', value: 'Low', color: '#16A34A' },
      { label: 'Stable for', value: '4 days', color: '#111827' },
      { label: 'Affected area', value: '0.8 km²', color: '#111827' },
      { label: 'Alert level', value: 'None', color: '#16A34A' },
    ],
  },
};

function ForecastDetail({ location, onBack }) {
  const d = FORECAST_DETAILS[location.kind] || FORECAST_DETAILS.green;
  const isHigh = location.kind === 'red';
  const isMed = location.kind === 'orange';
  const labelColor = isHigh ? '#E94B4B' : isMed ? '#F08537' : '#16A34A';
  const labelBg = isHigh ? '#FEE2E2' : isMed ? '#FEF3E2' : '#DCFCE7';
  const labelText = isHigh ? 'HIGH RISK' : isMed ? 'MEDIUM RISK' : 'LOW RISK';

  const W = 280, H = 120, days = ['Today', 'Tomorrow', 'Day 2', 'Day 3', 'Day 4'];
  const xs = days.map((_, i) => 20 + i * ((W - 40) / 4));
  const ys = d.chartPoints.map(p => 10 + (p / 100) * (H - 20));
  const pathD = xs.map((x, i) => `${i === 0 ? 'M' : 'L'} ${x} ${ys[i]}`).join(' ');
  const areaD = pathD + ` L ${xs[xs.length-1]} ${H} L ${xs[0]} ${H} Z`;

  return (
    <div style={{ overflowY: 'auto', maxHeight: '100%' }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px 8px' }}>
        <button onClick={onBack} style={{ background: 'none', border: 'none', padding: 4, cursor: 'pointer', display: 'flex' }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M15 6L9 12l6 6" stroke="#111827" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <span style={{ fontWeight: 700, fontSize: 16, color: '#111827' }}>Forecast Details</span>
      </div>

      {/* location card */}
      <div style={{ margin: '0 16px 16px', background: labelBg, borderRadius: 14, padding: '12px 14px', display: 'flex', alignItems: 'flex-start', gap: 10 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          {isHigh
            ? <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M12 3L2 21h20L12 3z" fill={labelColor} opacity="0.2" stroke={labelColor} strokeWidth="1.8" strokeLinejoin="round"/><line x1="12" y1="10" x2="12" y2="15" stroke={labelColor} strokeWidth="1.8" strokeLinecap="round"/><circle cx="12" cy="18" r="1" fill={labelColor}/></svg>
            : <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><polyline points="4,17 9,12 13,15 20,7" stroke={labelColor} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
          }
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: '#111827' }}>{location.name}</div>
          <div style={{ fontSize: 13, color: labelColor, marginTop: 2 }}>{d.prediction}</div>
        </div>
        <span style={{ fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 999, background: '#fff', color: labelColor, flexShrink: 0 }}>{labelText}</span>
      </div>

      {/* chart */}
      <div style={{ margin: '0 16px 16px' }}>
        <div style={{ fontWeight: 700, fontSize: 14, color: '#111827', marginBottom: 10 }}>Risk level over time</div>
        <div style={{ position: 'relative' }}>
          <svg width="100%" viewBox={`0 0 ${W} ${H + 30}`} style={{ overflow: 'visible' }}>
            {/* y-axis labels */}
            {['High', 'Medium', 'Low'].map((lbl, i) => (
              <text key={lbl} x="2" y={14 + i * 48} fontSize="9" fill="#9CA3AF" dominantBaseline="middle">{lbl}</text>
            ))}
            {/* grid lines */}
            {[0,1,2].map(i => (
              <line key={i} x1="32" y1={10 + i * 48} x2={W} y2={10 + i * 48} stroke="#F3F4F6" strokeWidth="1"/>
            ))}
            {/* area */}
            <defs>
              <linearGradient id="fg" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={d.chartColor} stopOpacity="0.25"/>
                <stop offset="100%" stopColor={d.chartColor} stopOpacity="0.02"/>
              </linearGradient>
            </defs>
            <path d={`M ${xs[0]} ${ys[0]} ` + xs.slice(1).map((x,i)=>`L ${x} ${ys[i+1]}`).join(' ') + ` L ${xs[xs.length-1]} ${H} L ${xs[0]} ${H} Z`} fill="url(#fg)"/>
            {/* line */}
            <polyline points={xs.map((x,i)=>`${x},${ys[i]}`).join(' ')} fill="none" stroke={d.chartColor} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
            {/* dots */}
            {xs.map((x,i) => <circle key={i} cx={x} cy={ys[i]} r="4" fill="#fff" stroke={d.chartColor} strokeWidth="2"/>)}
            {/* x-axis labels */}
            {days.map((lbl, i) => (
              <text key={lbl} x={xs[i]} y={H + 20} fontSize="9" fill="#9CA3AF" textAnchor="middle">{lbl}</text>
            ))}
          </svg>
        </div>
      </div>

      {/* stats row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, margin: '0 16px 16px' }}>
        {d.stats.map(s => (
          <div key={s.label} style={{ background: '#F9FAFB', borderRadius: 12, padding: '10px 12px' }}>
            <div style={{ fontSize: 11, color: '#6B7280', marginBottom: 2 }}>{s.label}</div>
            <div style={{ fontWeight: 700, fontSize: 15, color: s.color }}>{s.value}</div>
          </div>
        ))}
      </div>

      {/* reasons */}
      <div style={{ margin: '0 16px 24px' }}>
        <div style={{ fontWeight: 700, fontSize: 14, color: '#111827', marginBottom: 12 }}>Why this area is at risk?</div>
        <div style={{ display: 'flex', gap: 10 }}>
          {d.reasons.map((r, i) => (
            <div key={i} style={{ flex: 1, background: '#F9FAFB', borderRadius: 14, padding: '12px 8px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, textAlign: 'center' }}>
              <span style={{ fontSize: 24 }}>{r.icon}</span>
              <span style={{ fontSize: 11, color: '#374151', lineHeight: 1.3, whiteSpace: 'pre-line' }}>{r.label}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function TrendArrow({ trend }) {
  if (trend === 'rising') return <span className="tr tr-rising">↑ rising</span>;
  if (trend === 'stable') return <span className="tr tr-stable">→ stable</span>;
  if (trend === 'improving') return <span className="tr tr-improving">↓ improving</span>;
  return <span className="tr tr-good">↓ good</span>;
}

function dotColor(k) {
  return k === 'red' ? '#E94B4B' : k === 'orange' ? '#F08537' : k === 'yellow' ? '#F4C53B' : '#3DB85C';
}
function scoreColor(k) {
  return k === 'red' ? '#E94B4B' : k === 'orange' ? '#F08537' : k === 'yellow' ? '#D9A21B' : '#16A34A';
}

function MapSheet({ open, expanded, onSetExpanded, onClose }) {
  const [tab, setTab] = React.useState('Overview');
  const [selected, setSelected] = React.useState(null);
  const [forecastSelected, setForecastSelected] = React.useState(null);

  // touch swipe state
  const startY = React.useRef(null);
  const startState = React.useRef(null);
  const scrollRef = React.useRef(null);

  const onTouchStart = (e) => {
    startY.current = e.touches[0].clientY;
    startState.current = expanded;
  };
  const onTouchMove = (e) => {
    if (startY.current == null) return;
    const dy = e.touches[0].clientY - startY.current;
    // Don't collapse while the scroll container still has content above
    if (dy > 0 && scrollRef.current && scrollRef.current.scrollTop > 0) return;
    if (dy < -40 && !startState.current) onSetExpanded(true);
    if (dy > 60 && startState.current) onSetExpanded(false);
  };
  const onTouchEnd = () => {startY.current = null;};

  if (!open) return null;

  if (selected) {
    const L = selected;
    return (
      <div className="map-sheet map-sheet--detail">
        <div className="sheet-handle" onClick={() => setSelected(null)} />
        <div className="sheet-detail-head">
          <div>
            <h2 className="detail-title">{L.name}</h2>
            <div className="detail-sub">{L.zone} &nbsp; {L.region}</div>
          </div>
          <span className="risk-pill" style={{ background: '#FCE5E5', color: '#C73838' }}>Risk {L.score}</span>
        </div>
        <div className="stat-tiles">
          <div className="stat-tile stat-tile--danger">
            <div className="stat-tile-num">{L.score}</div>
            <div className="stat-tile-lbl">Risk score</div>
          </div>
          <div className="stat-tile">
            <div className="stat-tile-num">{L.quality}</div>
            <div className="stat-tile-lbl">Quality<br />score</div>
          </div>
          <div className="stat-tile">
            <div className="stat-tile-num">{L.reportsToday}</div>
            <div className="stat-tile-lbl">Reports<br />today</div>
          </div>
        </div>
        <div className="ai-card">
          <div className="ai-icon">
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="9" stroke="#3B5BDB" strokeWidth="2.5" fill="none" />
            </svg>
          </div>
          <div className="ai-body">
            <div className="ai-title">AI trace - probable source</div>
            <div className="ai-text">{L.aiBody}</div>
          </div>
        </div>
        <div className="detail-actions">
          <button className="btn btn-primary">Report issue</button>
          <button className="btn btn-secondary">Report issue</button>
          <button className="btn-icon" aria-label="Share">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <circle cx="6" cy="12" r="2.5" stroke="#1f2937" strokeWidth="1.8" />
              <circle cx="18" cy="6" r="2.5" stroke="#1f2937" strokeWidth="1.8" />
              <circle cx="18" cy="18" r="2.5" stroke="#1f2937" strokeWidth="1.8" />
              <line x1="8" y1="11" x2="16" y2="7" stroke="#1f2937" strokeWidth="1.8" />
              <line x1="8" y1="13" x2="16" y2="17" stroke="#1f2937" strokeWidth="1.8" />
            </svg>
          </button>
        </div>
      </div>);

  }

  return (
    <div
      className={`map-sheet ${expanded ? 'is-expanded' : 'is-peek'}`}
      onTouchStart={onTouchStart}
      onTouchMove={onTouchMove}
      onTouchEnd={onTouchEnd}
      onClick={!expanded ? () => onSetExpanded(true) : undefined}>
      
      <div className="sheet-handle" onClick={(e) => { e.stopPropagation(); onSetExpanded(!expanded); }} />
      <div className="sheet-tabs">
        {['Overview', 'Forecast'].map((t) =>
        <button key={t} className={`sheet-tab ${tab === t ? 'is-active' : ''}`} onClick={() => setTab(t)}>{t}</button>
        )}
      </div>
      {tab === 'Overview' &&
      <div className="sheet-list">
          {LOCATIONS.map((L) =>
        <button key={L.id} className="loc-row" onClick={() => setSelected(L)}>
              <span className="loc-dot" style={{ background: dotColor(L.kind) }} />
              <div className="loc-body">
                <div className="loc-name">{L.name}</div>
                <div className="loc-sub">{L.sub}</div>
              </div>
              <div className="loc-score">
                <div className="loc-score-num" style={{ color: scoreColor(L.kind) }}>{L.score}</div>
                <TrendArrow trend={L.trend} />
              </div>
            </button>
        )}
        </div>
      }
      {tab === 'Forecast' && forecastSelected &&
        <ForecastDetail location={forecastSelected} onBack={() => setForecastSelected(null)} />
      }
      {tab === 'Forecast' && !forecastSelected &&
      <div ref={scrollRef} style={{ padding: '4px 0 16px', overflowY: 'auto', flex: 1, WebkitOverflowScrolling: 'touch' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 16px 12px' }}>
          <span style={{ fontWeight: 700, fontSize: 16, color: '#111827' }}>High risk zones in next 48h</span>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="9" stroke="#9CA3AF" strokeWidth="1.8"/>
            <line x1="12" y1="11" x2="12" y2="16" stroke="#9CA3AF" strokeWidth="1.8" strokeLinecap="round"/>
            <circle cx="12" cy="8" r="1" fill="#9CA3AF"/>
          </svg>
        </div>
        {LOCATIONS.map((L) => {
          const isHigh = L.kind === 'red';
          const isMed = L.kind === 'orange';
          const iconBg = isHigh ? '#FEE2E2' : isMed ? '#FEF3E2' : '#DCFCE7';
          const labelBg = isHigh ? '#FEE2E2' : isMed ? '#FEF3E2' : '#DCFCE7';
          const labelColor = isHigh ? '#E94B4B' : isMed ? '#F08537' : '#16A34A';
          const labelText = isHigh ? 'HIGH RISK' : isMed ? 'MEDIUM RISK' : 'LOW RISK';
          const forecastColor = isHigh ? '#E94B4B' : isMed ? '#F08537' : '#16A34A';
          return (
            <div key={L.id} onClick={() => setForecastSelected(L)} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '10px 16px', borderBottom: '1px solid #F3F4F6', cursor: 'pointer',
            }}>
              <div style={{
                width: 42, height: 42, borderRadius: 12, background: iconBg,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                {isHigh
                  ? <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M12 3L2 21h20L12 3z" fill={labelColor} opacity="0.15" stroke={labelColor} strokeWidth="1.8" strokeLinejoin="round"/><line x1="12" y1="10" x2="12" y2="15" stroke={labelColor} strokeWidth="1.8" strokeLinecap="round"/><circle cx="12" cy="18" r="1" fill={labelColor}/></svg>
                  : <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><polyline points="4,17 9,12 13,15 20,7" stroke={labelColor} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/><polyline points="15,7 20,7 20,12" stroke={labelColor} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
                }
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14, color: '#111827' }}>{L.name}</div>
                <div style={{ fontSize: 13, color: forecastColor, fontWeight: 500 }}>{L.forecast}</div>
                <div style={{ fontSize: 12, color: '#9CA3AF' }}>Confidence: {L.confidence}%</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
                <span style={{
                  fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 999,
                  background: labelBg, color: labelColor, letterSpacing: 0.3,
                }}>{labelText}</span>
                <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
                  <path d="M1 1l6 6-6 6" stroke="#D1D5DB" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
            </div>
          );
        })}
      </div>
      }
    </div>);

}

window.MapSheet = MapSheet;