// Per-track properties — volume slider, mute toggle, background colour/blur
// for letterboxing video tracks. V22 adds AI Magic Tools section.

'use client';

import { Volume1, ImageIcon, Sparkles, Mic, Sliders, ZoomIn, Activity } from 'lucide-react';
import { useEditor } from '@/store/editor';
import type { Track, AITrackSettings } from '@/types';
import { Section, Row, Slider } from './FormFields';

export function TrackProperties({ track }: { track: Track }) {
  const updateTrack = useEditor((s) => s.updateTrack);

  const bgColor = track.background?.color ?? '#000000';
  const bgBlur = track.background?.blur ?? false;
  const nrEnabled = track.noiseReduction?.enabled ?? false;
  const nrAmount = track.noiseReduction?.amount ?? 0.5;

  function setNoiseReduction(patch: Partial<NonNullable<Track['noiseReduction']>>) {
    const current = track.noiseReduction ?? { enabled: false, amount: 0.5 };
    updateTrack(track.id, { noiseReduction: { ...current, ...patch } });
  }

  function setAI(patch: Partial<AITrackSettings>) {
    const current: AITrackSettings = track.ai ?? {};
    updateTrack(track.id, { ai: { ...current, ...patch } });
  }

  return (
    <Section title={`แทร็ก: ${track.name}`} icon={<Volume1 size={14} />}>
      <div className="space-y-2">
        <Row label="ประเภท" value={track.kind === 'video' ? 'วิดีโอ' : 'เสียง'} />

        {track.kind === 'audio' && (
          <>
            <Slider
              label={`ระดับเสียง ${Math.round(track.volume * 100)}%`}
              min={0}
              max={1.5}
              step={0.01}
              value={track.volume}
              onChange={(v) => updateTrack(track.id, { volume: v })}
            />
            <label className="flex items-center gap-2 text-xs">
              <input
                type="checkbox"
                checked={track.muted}
                onChange={(e) => updateTrack(track.id, { muted: e.target.checked })}
              />
              ปิดเสียงแทร็กนี้
            </label>

            {/* Noise reduction — uses FFmpeg's afftdn filter at export time */}
            <div className="pt-2 mt-2 border-t border-capcut-border/50 space-y-2">
              <label className="flex items-center gap-2 text-xs">
                <input
                  type="checkbox"
                  checked={nrEnabled}
                  onChange={(e) =>
                    setNoiseReduction({ enabled: e.target.checked })
                  }
                />
                <Sparkles size={11} className="text-capcut-blue" />
                <span>ตัดเสียงรบกวน (Noise Reduction)</span>
              </label>
              {nrEnabled && (
                <>
                  <Slider
                    label={`ความแรง ${Math.round(nrAmount * 100)}%`}
                    min={0}
                    max={1}
                    step={0.05}
                    value={nrAmount}
                    onChange={(v) => setNoiseReduction({ amount: v })}
                  />
                  <p className="text-[10px] text-capcut-muted">
                    ใช้ FFT denoise (afftdn) — ลดเสียงฮัม/ลม/เสียงรบกวนพื้นหลัง
                    ค่าสูงจะตัด noise แรงแต่อาจทำให้เสียงพูดแหบ
                  </p>
                </>
              )}
            </div>
          </>
        )}

        {track.kind === 'video' && (
          <>
            <div className="flex items-center gap-2 text-xs">
              <ImageIcon size={12} />
              <span className="flex-1">สีพื้นหลัง</span>
              <input
                type="color"
                value={bgColor}
                onChange={(e) =>
                  updateTrack(track.id, {
                    background: { color: e.target.value, blur: bgBlur },
                  })
                }
                className="w-7 h-7 rounded border border-capcut-border bg-transparent"
              />
            </div>
            <label className="flex items-center gap-2 text-xs">
              <input
                type="checkbox"
                checked={bgBlur}
                onChange={(e) =>
                  updateTrack(track.id, {
                    background: { color: bgColor, blur: e.target.checked },
                  })
                }
              />
              เบลอพื้นหลัง (สำหรับวิดีโอที่ aspect ไม่พอดี)
            </label>
          </>
        )}

        {/* V22 AI Magic Tools — Voice processing + Auto-Zoom + Heatmap */}
        <div className="pt-2 mt-2 border-t border-capcut-border/50 space-y-2">
          <div className="flex items-center gap-1.5 text-[11px] text-capcut-orange font-semibold">
            <Sparkles size={12} className="text-capcut-orange" /> AI Magic Tools
          </div>

          {/* Voice Isolation — audio tracks only */}
          {track.kind === 'audio' && (
            <>
              <label className="flex items-center gap-2 text-xs">
                <input
                  type="checkbox"
                  checked={track.ai?.voiceIsolation?.enabled ?? false}
                  onChange={(e) =>
                    setAI({
                      voiceIsolation: {
                        ...track.ai?.voiceIsolation,
                        enabled: e.target.checked,
                        lowHz: track.ai?.voiceIsolation?.lowHz ?? 80,
                        highHz: track.ai?.voiceIsolation?.highHz ?? 8000,
                      },
                    })
                  }
                />
                <Mic size={11} className="text-capcut-blue" />
                <span>แยกเสียงพูด (Voice Isolation)</span>
              </label>
              {track.ai?.voiceIsolation?.enabled && (
                <>
                  <Slider
                    label={`ความถี่ต่ำ ${track.ai.voiceIsolation.lowHz ?? 80} Hz`}
                    min={40}
                    max={200}
                    step={5}
                    value={track.ai.voiceIsolation.lowHz ?? 80}
                    onChange={(v) =>
                      setAI({
                        voiceIsolation: {
                          ...track.ai?.voiceIsolation,
                          enabled: true,
                          lowHz: v,
                          highHz: track.ai?.voiceIsolation?.highHz ?? 8000,
                        },
                      })
                    }
                  />
                  <Slider
                    label={`ความถี่สูง ${track.ai.voiceIsolation.highHz ?? 8000} Hz`}
                    min={3000}
                    max={12000}
                    step={100}
                    value={track.ai.voiceIsolation.highHz ?? 8000}
                    onChange={(v) =>
                      setAI({
                        voiceIsolation: {
                          ...track.ai?.voiceIsolation,
                          enabled: true,
                          lowHz: track.ai?.voiceIsolation?.lowHz ?? 80,
                          highHz: v,
                        },
                      })
                    }
                  />
                </>
              )}

              <label className="flex items-center gap-2 text-xs pt-1">
                <input
                  type="checkbox"
                  checked={track.ai?.voiceEnhance?.enabled ?? false}
                  onChange={(e) =>
                    setAI({
                      voiceEnhance: {
                        ...track.ai?.voiceEnhance,
                        enabled: e.target.checked,
                        thresholdDb: track.ai?.voiceEnhance?.thresholdDb ?? -20,
                        ratio: track.ai?.voiceEnhance?.ratio ?? 4,
                      },
                    })
                  }
                />
                <Sliders size={11} className="text-capcut-purple" />
                <span>เพิ่มความชัดเสียงพูด (Voice Enhance)</span>
              </label>
            </>
          )}

          {/* Auto-Zoom on Speech — video tracks only */}
          {track.kind === 'video' && (
            <>
              <label className="flex items-center gap-2 text-xs">
                <input
                  type="checkbox"
                  checked={track.ai?.autoZoom ?? false}
                  onChange={(e) => setAI({ autoZoom: e.target.checked })}
                />
                <ZoomIn size={11} className="text-capcut-blue" />
                <span>Auto-Zoom ตอนพูด</span>
              </label>
              {track.ai?.autoZoom && (
                <Slider
                  label={`ระดับ zoom ${(track.ai.autoZoomFactor ?? 1.25).toFixed(2)}×`}
                  min={1.0}
                  max={2.0}
                  step={0.05}
                  value={track.ai.autoZoomFactor ?? 1.25}
                  onChange={(v) => setAI({ autoZoomFactor: v })}
                />
              )}
            </>
          )}

          {/* Engagement Heatmap toggle */}
          <label className="flex items-center gap-2 text-xs">
            <input
              type="checkbox"
              checked={track.ai?.heatmapVisible ?? false}
              onChange={(e) => setAI({ heatmapVisible: e.target.checked })}
            />
            <Activity size={11} className="text-capcut-orange" />
            <span>แสดง Heatmap (Engagement)</span>
          </label>
        </div>
      </div>
    </Section>
  );
}