// Per-track properties — volume slider, mute toggle, background colour/blur
// for letterboxing video tracks, and Picture-in-Picture placement for
// non-base video tracks.

'use client';

import { Volume1, ImageIcon, Sparkles, LayoutGrid } from 'lucide-react';
import { useEditor } from '@/store/editor';
import type { Track, VideoPosition } from '@/types';
import { Section, Row, Slider } from './FormFields';

const VIDEO_POSITIONS: { value: VideoPosition; label: string; icon: string }[] = [
  { value: 'full', label: 'เต็มจอ', icon: '▣' },
  { value: 'pip-tl', label: 'บนซ้าย', icon: '◱' },
  { value: 'pip-tr', label: 'บนขวา', icon: '◲' },
  { value: 'pip-bl', label: 'ล่างซ้าย', icon: '◰' },
  { value: 'pip-br', label: 'ล่างขวา', icon: '◳' },
  { value: 'pip-c', label: 'กลาง', icon: '◈' },
];

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

  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;
  const videoPos: VideoPosition = track.videoPosition ?? 'full';
  const videoScale = track.videoScale ?? (videoPos === 'full' ? 1 : 0.3);
  const videoOpacity = track.videoOpacity ?? 1;
  const isBaseVideo =
    track.kind === 'video' &&
    allTracks.filter((t) => t.kind === 'video')[0]?.id === track.id;

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

            {/* Multi-video layout (only meaningful for non-base video tracks) */}
            {!isBaseVideo && (
              <div className="pt-2 mt-2 border-t border-capcut-border/50 space-y-2">
                <div className="flex items-center gap-2 text-xs text-capcut-muted">
                  <LayoutGrid size={11} />
                  <span>ตำแหน่งวิดีโอซ้อน (Picture-in-Picture)</span>
                </div>
                <div className="grid grid-cols-3 gap-1">
                  {VIDEO_POSITIONS.map((p) => (
                    <button
                      key={p.value}
                      type="button"
                      onClick={() =>
                        updateTrack(track.id, {
                          videoPosition: p.value,
                          videoScale: p.value === 'full' ? 1 : videoScale,
                        })
                      }
                      className={`px-2 h-8 rounded text-xs flex items-center justify-center gap-1 ${
                        videoPos === p.value
                          ? 'bg-capcut-blue/20 text-capcut-blue border border-capcut-blue/40'
                          : 'bg-capcut-surface hover:bg-capcut-border text-capcut-text'
                      }`}
                      title={p.label}
                    >
                      <span className="text-base leading-none">{p.icon}</span>
                      <span>{p.label}</span>
                    </button>
                  ))}
                </div>
                {videoPos !== 'full' && (
                  <>
                    <Slider
                      label={`ขนาด ${Math.round(videoScale * 100)}%`}
                      min={0.1}
                      max={1}
                      step={0.05}
                      value={videoScale}
                      onChange={(v) => updateTrack(track.id, { videoScale: v })}
                    />
                    <Slider
                      label={`ความโปร่งใส ${Math.round(videoOpacity * 100)}%`}
                      min={0}
                      max={1}
                      step={0.05}
                      value={videoOpacity}
                      onChange={(v) => updateTrack(track.id, { videoOpacity: v })}
                    />
                  </>
                )}
              </div>
            )}
            {isBaseVideo && (
              <p className="text-[10px] text-capcut-muted pt-1">
                ⓘ แทร็กวิดีโอหลัก (เต็มจอ) — แทร็กอื่นจะซ้อนบนนี้
              </p>
            )}
          </>
        )}
      </div>
    </Section>
  );
}
