/* global React, ReactDOM */
const { useState, useCallback, useRef, useEffect } = React;



function App() {
  const [stage, setStage] = useState("upload"); // upload | processing | dashboard
  const [file, setFile] = useState(null);
  const [result, setResult] = useState(null);
  const [pendingResult, setPendingResult] = useState(null);
  const [error, setError] = useState(null);
  const [activeId, setActiveId] = useState(null);
  const [hoverId, setHoverId] = useState(null);

  const [audioUrl, setAudioUrl] = useState(null);
  const audioRef = useRef(null);
  const [currentTime, setCurrentTime] = useState(0);
  const [playing, setPlaying] = useState(false);
  const wsRef = useRef(null);

  const duration = result?.timeline?.[result.timeline.length - 1]?.end || 0;

  useEffect(() => {
    if (!result) return;
    const seg = result.timeline.find(s => currentTime >= s.start && currentTime < s.end);
    if (seg && seg.id !== activeId) setActiveId(seg.id);
  }, [currentTime, result]);

  useEffect(() => {
    if (stage === "dashboard" && audioUrl) {
      const ws = WaveSurfer.create({
        container: '#waveform',
        waveColor: '#444',
        progressColor: '#ff4d4d',
        height: 50,
        media: audioRef.current
      });
      wsRef.current = ws;
      
      ws.on('play', () => setPlaying(true));
      ws.on('pause', () => setPlaying(false));

      ws.load(audioUrl);
      return () => ws.destroy();
    }
  }, [stage, audioUrl]);

  const togglePlay = () => {
    if (wsRef.current) wsRef.current.playPause();
  };

  const onSelectSegment = (id) => {
    setActiveId(id);
    const seg = result.timeline.find((s, idx) => (s.id !== undefined ? s.id === id : idx === id));
    if (seg && audioRef.current) {
      audioRef.current.currentTime = seg.start;
      audioRef.current.play();
    }
  };

  const onAnalyze = async (f) => {
    setFile(f);
    setAudioUrl(URL.createObjectURL(f));
    setStage("processing");
    setError(null);

    const formData = new FormData();
    formData.append("file", f);

    try {
      const response = await fetch(`${window.API_URL}/analyze`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error(`Server responded with ${response.status}`);
      }

      const data = await response.json();
      
      // Inject auto-generated IDs if missing for timeline selection
      if (data.timeline) {
        data.timeline = data.timeline.map((s, i) => ({ ...s, id: i }));
      }

      // Normalize evidence: API returns List[str], UI expects List[Dict]
      if (data.evidence && Array.isArray(data.evidence)) {
        data.evidence = data.evidence.map((phrase, i) => {
          const matchingSegment = data.timeline.find(s => s.text.includes(phrase));
          return {
            id: `e${i}`,
            phrase: phrase,
            category: matchingSegment?.tactic || "Scam Indicator",
            severity: matchingSegment?.scam_signal > 0.8 ? "critical" : "high",
            segment_id: matchingSegment?.id || 0
          };
        });
      }

      setPendingResult(data);
    } catch (err) {
      console.error("API Error:", err);
      setError(err.message);
      setStage("upload");
    }
  };
  
  const onReset = () => {
    setStage("upload"); 
    setFile(null); 
    setResult(null);
    setPendingResult(null);
    setError(null);
    setActiveId(null);
    setCurrentTime(0); 
    if (audioUrl) {
      URL.revokeObjectURL(audioUrl);
      setAudioUrl(null);
    }
  };

  return (
    <>
      <TopBar stage={stage} onReset={onReset}/>
      {stage === "upload" && (
        <div style={{position:'relative'}}>
          {error && (
            <div className="error-toast">
              <b>Analysis failed:</b> {error}
            </div>
          )}
          <UploadStage onAnalyze={onAnalyze}/>
        </div>
      )}
      {stage === "processing" && (
        <ProcessingStage 
          file={file} 
          isReady={!!pendingResult} 
          onDone={() => { setResult(pendingResult); setStage("dashboard"); setPendingResult(null); }}
        />
      )}
      {stage === "dashboard" && result && (
        <div className="dash">
          <div className="dash-head">
            <div>
              <div className="dh-eyebrow">Analysis report</div>
              <h2 className="dh-title">{file?.name}</h2>
              <div className="file-meta">
                <span><b>{Math.round(duration)}s</b> call</span>
                <span className="sep">·</span>
                <span>{file ? (file.size / (1024 * 1024)).toFixed(1) : "0"} MB</span>
                <span className="sep">·</span>
                <span>analyzed {new Date().toLocaleString(undefined, {month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}</span>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '16px', background: 'var(--panel-bg)', borderRadius: '100px', border: '1px solid var(--line-1)', padding: '6px 16px' }}>
              <button className="ap-btn" onClick={togglePlay} aria-label={playing ? "Pause" : "Play"} style={{ background: 'transparent', border: 'none', color: 'var(--text-1)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
                {playing ? (
                  <svg width="12" height="14" viewBox="0 0 11 12" fill="none">
                    <rect x="0" y="0" width="3.5" height="12" rx="1.5" fill="currentColor"/>
                    <rect x="7.5" y="0" width="3.5" height="12" rx="1.5" fill="currentColor"/>
                  </svg>
                ) : (
                  <svg width="14" height="14" viewBox="0 0 11 12" fill="none">
                    <path d="M1 1 L10 6 L1 11 Z" fill="currentColor"/>
                  </svg>
                )}
              </button>
              <div style={{ fontSize: '13px', fontFamily: 'var(--font-mono)', color: 'var(--text-2)' }}>
                {Math.floor(currentTime / 60)}:{(Math.floor(currentTime % 60)).toString().padStart(2, "0")} / {Math.floor(duration / 60)}:{(Math.floor(duration % 60)).toString().padStart(2, "0")}
              </div>
              <audio 
                ref={audioRef} 
                src={audioUrl} 
                onTimeUpdate={(e) => setCurrentTime(e.target.currentTime)} 
                style={{ display: 'none' }}
              />
            </div>
          </div>
          
          <div style={{ backgroundColor: 'var(--panel-bg)', padding: '10px 24px', borderRadius: '12px', border: '1px solid var(--line-1)', marginBottom: '16px', marginTop: '-4px' }}>
            <div id="waveform" style={{width: '100%'}}></div>
          </div>

          <VerdictCard summary={result.summary} />

          <div className="dash-grid">
            <div className="dash-col-main">
              <Timeline
                timeline={result.timeline}
                duration={duration}
                activeId={activeId}
                onSelect={onSelectSegment}
                onHover={setHoverId}
                currentTime={currentTime}
              />
              <RiskGraph
                timeline={result.timeline}
                duration={duration}
                activeId={activeId}
                onSelect={onSelectSegment}
              />
              <Transcript
                timeline={result.timeline}
                roles={result.roles}
                evidence={result.evidence}
                activeId={activeId}
                hoverId={hoverId}
                onSelect={onSelectSegment}
              />
            </div>
            <div className="dash-col-side">
              <RolesPanel roles={result.roles}/>
              <EvidencePanel evidence={result.evidence} onSelect={onSelectSegment}/>
              <AudioPanel audio={result.audio_analysis}/>
              <ReliabilityPanel summary={result.summary} audio={result.audio_analysis} roles={result.roles}/>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
