/* SolarDose — SVG enstrüman bileşenleri (responsive, profil-tabanlı) */

const SDT = {
  ink: '#f7ebd7', text: '#33271a',
  mute: 'rgba(51,39,26,0.60)', mute2: 'rgba(51,39,26,0.38)',
  line: 'rgba(51,39,26,0.16)', line2: 'rgba(51,39,26,0.08)',
  mono: "'Figtree', -apple-system, BlinkMacSystemFont, sans-serif",
};

/* DialInstrument — 24h dış halka + gerçek güneş yörüngesi (altitude domu).
   props: profile (SD.dayProfile çıktısı), loc, markerDate, accent, size */
function DialInstrument({ profile, loc, markerDate, accent = 'var(--accent)' }) {
  const size = 1000; // viewBox; CSS ile ölçeklenir
  const c = size / 2;
  const rOuter = c - 18;
  const rTick = c - 34;
  const rMin = c - 250;   // ufuk yarıçapı (alt=0)
  const rMax = c - 70;    // tepe yarıçapı (alt=maxAlt)
  const { samples, noonAlt, sunrise, sunset, safeStart, safeEnd } = profile;
  const maxAlt = Math.max(noonAlt, 1);

  // gün-fraksiyonu → açı: sol(π)=00:00 değil; doğuş→batış yayını kullan
  const t0 = sunrise ? sunrise.getTime() : 0;
  const t1 = sunset ? sunset.getTime() : 1;
  const span = Math.max(t1 - t0, 1);
  const frac = (d) => (d.getTime() - t0) / span;          // 0..1
  const angleOf = (f) => Math.PI * (1 - f);               // π(sol)→0(sağ)
  const radiusOf = (alt) => rMin + (Math.max(0, alt) / maxAlt) * (rMax - rMin);
  const pt = (d, alt) => {
    const th = angleOf(frac(d));
    const r = radiusOf(alt);
    return [c + r * Math.cos(th), c - r * Math.sin(th)];
  };

  // güneş yolu (doğuş→batış, alt>0)
  console.log('[DIAL] sunrise:', sunrise?.toISOString(), 'sunset:', sunset?.toISOString());
  console.log('[DIAL] samples[0]:', samples[0]?.t.toISOString(), 'samples last:', samples[samples.length-1]?.t.toISOString());
  console.log('[DIAL] pathPts count:', samples.filter((s) => s.alt > -1 && s.t >= sunrise && s.t <= sunset).length);
  const pathPts = samples.filter((s) => s.alt > -1 && s.t >= sunrise && s.t <= sunset).map((s) => pt(s.t, s.alt));
  const pathD = pathPts.length ? 'M' + pathPts.map((p) => p.map((n) => n.toFixed(1)).join(',')).join(' L') : '';
  // güvenli yay (alt>=eşik)
  const safePts = (safeStart && safeEnd)
    ? samples.filter((s) => s.t >= safeStart && s.t <= safeEnd && s.alt >= 0).map((s) => pt(s.t, s.alt))
    : [];
  const safeD = safePts.length ? 'M' + safePts.map((p) => p.map((n) => n.toFixed(1)).join(',')).join(' L') : '';

  // marker
  const mAlt = Math.max(0, SD.altDeg(markerDate, loc.lat, loc.lon));
  const inDay = markerDate >= sunrise && markerDate <= sunset;
  const [mx, my] = inDay ? pt(markerDate, mAlt) : [c, c + rMin];
  // İşaretçi→merkez ışınını, ortadaki büyük sayıya binmemesi için merkeze ~210 birim
  // kala durdur (sayının yarı yüksekliğinin dışında kalır).
  const mdx = c - mx, mdy = c - my, mlen = Math.hypot(mdx, mdy) || 1;
  const rStop = 210, tt = Math.max(0, (mlen - rStop) / mlen);
  const lx = mx + mdx * tt, ly = my + mdy * tt;

  return (
    <svg viewBox={`0 0 ${size} ${size}`} style={{ display: 'block', width: '100%', height: '100%' }}>
      <circle cx={c} cy={c} r={rOuter} fill="none" stroke={SDT.line} strokeWidth="1.5" />
      {/* saat tikleri */}
      {Array.from({ length: 24 }).map((_, i) => {
        const ang = -Math.PI / 2 + (i / 24) * 2 * Math.PI;
        const major = i % 3 === 0;
        const r2 = major ? rTick - 16 : rTick - 8;
        return (
          <line key={i}
            x1={c + rTick * Math.cos(ang)} y1={c + rTick * Math.sin(ang)}
            x2={c + r2 * Math.cos(ang)} y2={c + r2 * Math.sin(ang)}
            stroke={major ? SDT.mute : SDT.line} strokeWidth={major ? 1.5 : 1} />
        );
      })}
      {[0, 6, 12, 18].map((h) => {
        const ang = -Math.PI / 2 + (h / 24) * 2 * Math.PI;
        const r = rTick - 40;
        return (
          <text key={h} x={c + r * Math.cos(ang)} y={c + r * Math.sin(ang) + 6}
            fontFamily={SDT.mono} fontSize="20" fill={SDT.mute} textAnchor="middle" letterSpacing="1.5">
            {String(h).padStart(2, '0')}
          </text>
        );
      })}
      {/* ufuk */}
      <line x1={c - rMin - 40} x2={c + rMin + 40} y1={c} y2={c} stroke={SDT.line} strokeWidth="1.5" strokeDasharray="3 7" />
      {/* güneş yolu (soluk) */}
      {pathD && <path d={pathD} fill="none" stroke={SDT.mute2} strokeWidth="2" />}
      {/* güvenli yay (amber) */}
      {safeD && <path d={safeD} fill="none" stroke={accent} strokeWidth="4" />}
      {/* doğuş/batış işaretleri */}
      {sunrise && (<>
        <circle cx={pt(sunrise, 0)[0]} cy={pt(sunrise, 0)[1]} r="3.5" fill={SDT.mute} />
        <text x={pt(sunrise, 0)[0]} y={pt(sunrise, 0)[1] + 30} fontFamily={SDT.mono} fontSize="17" fill={SDT.mute2} textAnchor="middle" letterSpacing="1">{SD.fmtClockTz(sunrise, loc.tz)}</text>
      </>)}
      {sunset && (<>
        <circle cx={pt(sunset, 0)[0]} cy={pt(sunset, 0)[1]} r="3.5" fill={SDT.mute} />
        <text x={pt(sunset, 0)[0]} y={pt(sunset, 0)[1] + 30} fontFamily={SDT.mono} fontSize="17" fill={SDT.mute2} textAnchor="middle" letterSpacing="1">{SD.fmtClockTz(sunset, loc.tz)}</text>
      </>)}
      {/* marker */}
      {inDay && (<>
        <line x1={mx} y1={my} x2={lx} y2={ly} stroke={accent} strokeOpacity="0.18" strokeWidth="1.5" strokeDasharray="2 5" />
        <circle cx={mx} cy={my} r="15" fill={accent} />
        <circle cx={mx} cy={my} r="26" fill="none" stroke={accent} strokeOpacity="0.4" strokeWidth="1.5" />
        <circle cx={mx} cy={my} r="40" fill="none" stroke={accent} strokeOpacity="0.15" strokeWidth="1.5" />
      </>)}
    </svg>
  );
}

/* FitzRow — Fitzpatrick deri tipi seçici */
function FitzRow({ value, onChange, size = 38, gap = 12, labels = true }) {
  return (
    <div style={{ display: 'flex', gap, flexWrap: 'wrap' }}>
      {SD.SKIN.map((s) => {
        const sel = s.id === value;
        return (
          <button key={s.id} onClick={() => onChange && onChange(s.id)} aria-label={`Fitzpatrick Tip ${s.roman}`}
            style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7,
              background: 'none', border: 'none', padding: 0, cursor: 'pointer',
            }}>
            <span style={{
              width: size, height: size, borderRadius: '50%', background: s.color,
              boxShadow: sel ? `0 0 0 2px ${SDT.ink}, 0 0 0 4px var(--accent)` : 'inset 0 0 0 1px rgba(0,0,0,0.2)',
              transition: 'box-shadow .15s', display: 'block',
            }} />
            {labels && (
              <span style={{ fontFamily: SDT.mono, fontSize: 11, letterSpacing: '0.06em', color: sel ? SDT.text : SDT.mute2 }}>{s.roman}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

/* DayStrip — yatay altitude eğrisi (sonuç ekranında küçük referans) */
function DayStrip({ profile, loc, markerDate, w = 720, h = 150, accent = 'var(--accent)' }) {
  const padL = 8, padR = 8, padT = 14, padB = 26;
  const iw = w - padL - padR, ih = h - padT - padB;
  const { samples, noonAlt, sunrise, sunset, safeStart, safeEnd } = profile;
  const maxAlt = Math.max(noonAlt, 1);
  const tz = loc.tz ?? 0;
  const tzMs = tz * 3600000;
  const day0 = new Date(Date.UTC(
    new Date(sunrise.getTime() + tzMs).getUTCFullYear(),
    new Date(sunrise.getTime() + tzMs).getUTCMonth(),
    new Date(sunrise.getTime() + tzMs).getUTCDate()
  ) - tzMs);
  const xOf = (d) => padL + ((d.getTime() - day0.getTime()) / 86400000) * iw;
  const yOf = (alt) => padT + ih - (Math.max(0, alt) / maxAlt) * ih;
  const vis = samples.filter((s) => s.alt > 0);
  const line = vis.length ? 'M' + vis.map((s) => `${xOf(s.t).toFixed(1)},${yOf(s.alt).toFixed(1)}`).join(' L') : '';
  const area = line ? `${line} L${xOf(vis[vis.length - 1].t).toFixed(1)},${(padT + ih).toFixed(1)} L${xOf(vis[0].t).toFixed(1)},${(padT + ih).toFixed(1)} Z` : '';
  const safe = samples.filter((s) => safeStart && s.t >= safeStart && s.t <= safeEnd);
  const safeLine = safe.length ? 'M' + safe.map((s) => `${xOf(s.t).toFixed(1)},${yOf(s.alt).toFixed(1)}`).join(' L') : '';
  const thrY = yOf(SD.THRESHOLD);
  const [mx, my] = [xOf(markerDate), yOf(Math.max(0, SD.altDeg(markerDate, loc.lat, loc.lon)))];

  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ display: 'block', width: '100%', height: 'auto' }}>
      <defs>
        <linearGradient id="dsfill" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="var(--accent)" stopOpacity="0.14" />
          <stop offset="1" stopColor="var(--accent)" stopOpacity="0" />
        </linearGradient>
      </defs>
      <line x1={padL} x2={w - padR} y1={padT + ih} y2={padT + ih} stroke={SDT.line} strokeWidth="1" />
      <line x1={padL} x2={w - padR} y1={thrY} y2={thrY} stroke={SDT.line} strokeWidth="1" strokeDasharray="3 6" />
      <text x={w - padR} y={thrY - 6} fontFamily={SDT.mono} fontSize="13" fill={SDT.mute2} textAnchor="end" letterSpacing="1">α ≥ 35°</text>
      {area && <path d={area} fill="url(#dsfill)" />}
      {line && <path d={line} fill="none" stroke={SDT.mute2} strokeWidth="1.5" />}
      {safeLine && <path d={safeLine} fill="none" stroke={accent} strokeWidth="2.5" />}
      {[6, 9, 12, 15, 18].map((hr) => {
        const d = new Date(day0.getTime() + hr * 3600000);
        return <text key={hr} x={xOf(d)} y={h - 6} fontFamily={SDT.mono} fontSize="12" fill={SDT.mute2} textAnchor="middle" letterSpacing="1">{String(hr).padStart(2, '0')}</text>;
      })}
      <circle cx={mx} cy={my} r="5" fill={accent} />
    </svg>
  );
}

Object.assign(window, { DialInstrument, FitzRow, DayStrip, SDT });
