const { useState } = React;

const FaceList = ({ faces, onSeek }) => {
    const [expandedFaceId, setExpandedFaceId] = useState(null);

    const toggleFace = (faceId) => {
        setExpandedFaceId(expandedFaceId === faceId ? null : faceId);
    };

    const parseTime = (timeStr) => {
        if (typeof timeStr === 'number') return timeStr;
        if (!timeStr) return 0;
        const [h, m, s] = timeStr.split(':');
        return parseInt(h) * 3600 + parseInt(m) * 60 + parseFloat(s);
    };

    // Helper to safely get name (handles object with .value or string)
    const getName = (face) => {
        const n = face.name;
        if (typeof n === 'object' && n !== null) return n.value || face.face_id;
        return n || face.face_id;
    };

    if (!faces || faces.length === 0) {
        return (
            <div className="glass-panel rounded-2xl p-6 text-center text-slate-500">
                <p>No face detection data available.</p>
            </div>
        );
    }

    return (
        <div className="glass-panel rounded-2xl flex flex-col h-[600px] md:h-[800px] overflow-hidden">
            <div className="p-4 border-b border-slate-700/50 bg-slate-900/30">
                <h2 className="font-semibold text-slate-200 flex items-center gap-2">
                    <svg className="w-4 h-4 text-pink-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    Detected Faces ({faces.length})
                </h2>
            </div>

            <div className="flex-1 overflow-y-auto p-2 space-y-2 custom-scrollbar">
                {faces.map((face) => {
                    const isExpanded = expandedFaceId === face.face_id;
                    const bestFaceTime = face.timestamp_of_best_face;
                    const ocrMatch = face.ocr_name_match;
                    const displayName = getName(face);

                    return (
                        <div
                            key={face.face_id}
                            className={`
                                rounded-xl transition-all duration-200 border
                                ${isExpanded
                                    ? 'bg-slate-800/80 border-slate-600'
                                    : 'bg-slate-900/30 border-transparent hover:bg-slate-800/50 hover:border-slate-700/50'
                                }
                            `}
                        >
                            {/* Header / Summary Line */}
                            <div
                                onClick={() => toggleFace(face.face_id)}
                                className="p-4 cursor-pointer flex justify-between items-start gap-4"
                            >
                                <div className="flex-1">
                                    <div className="flex items-baseline justify-between mb-1">
                                        <span className="font-semibold text-slate-200">
                                            {displayName && face.face_id && displayName !== face.face_id
                                                ? `${displayName} (${face.face_id})`
                                                : displayName}
                                        </span>
                                        {face.confidence != null && (
                                            <span className="text-xs text-slate-500 bg-slate-800 px-1.5 py-0.5 rounded">
                                                {(face.confidence * 100).toFixed(0)}%
                                            </span>
                                        )}
                                    </div>

                                    {face.title && (
                                        <div className="text-xs text-sky-400 mb-1">{face.title}</div>
                                    )}

                                    <div className="text-xs text-slate-500 line-clamp-2">
                                        {face.description}
                                    </div>
                                </div>

                                <button className="text-slate-500 hover:text-slate-300 mt-1">
                                    <svg
                                        className={`w-4 h-4 transform transition-transform ${isExpanded ? 'rotate-180' : ''}`}
                                        fill="none" viewBox="0 0 24 24" stroke="currentColor"
                                    >
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                    </svg>
                                </button>
                            </div>

                            {/* Details (Expanded) */}
                            {isExpanded && (
                                <div className="px-4 pb-4 border-t border-slate-700/50 pt-3 animate-fade-in">

                                    {/* Quick Actions */}
                                    <div className="grid grid-cols-2 gap-2 mb-4">
                                        {bestFaceTime && (
                                            <button
                                                onClick={(e) => { e.stopPropagation(); onSeek(parseTime(bestFaceTime)); }}
                                                className="flex items-center justify-center gap-2 p-2 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-400 text-xs font-medium transition-colors border border-sky-500/20"
                                            >
                                                <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                                </svg>
                                                Best Face ({bestFaceTime})
                                            </button>
                                        )}

                                        {ocrMatch && ocrMatch.matched && (
                                            <button
                                                onClick={(e) => { e.stopPropagation(); onSeek(parseTime(ocrMatch.timestamp)); }}
                                                className="flex items-center justify-center gap-2 p-2 rounded bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-400 text-xs font-medium transition-colors border border-indigo-500/20"
                                            >
                                                <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 19v-8.93a2 2 0 01.89-1.664l7-4.666a2 2 0 012.22 0l7 4.666A2 2 0 0121 10.07V19M3 19a2 2 0 002 2h14a2 2 0 002-2M3 19l6.75-4.5M21 19l-6.75-4.5M3 10l6.75 4.5M21 10l-6.75 4.5m0 0l-1.14.76a2 2 0 01-2.22 0l-1.14-.76" />
                                                </svg>
                                                OCR Match ({ocrMatch.timestamp})
                                            </button>
                                        )}
                                    </div>

                                    {/* Screen Time Segments */}
                                    <div className="space-y-1">
                                        <div className="text-[10px] uppercase text-slate-500 font-semibold tracking-wider mb-1">Appearances</div>
                                        {face.screen_time.map((segment, idx) => (
                                            <div key={idx} className="flex flex-col p-3 rounded-lg bg-slate-900/50 text-xs text-slate-400 gap-2 border border-slate-800/50 hover:border-slate-700 hover:bg-slate-800/80 transition-all">
                                                <div className="flex items-center justify-between gap-4">
                                                    {/* Start Group */}
                                                    <div className="flex items-center gap-1">
                                                        <button
                                                            onClick={(e) => { e.stopPropagation(); onSeek(parseTime(segment.start)); }}
                                                            className="px-2 py-1 rounded bg-sky-500/10 border border-sky-500/20 text-sky-400 hover:bg-sky-500 hover:text-white font-mono font-medium transition-colors"
                                                            title={`Jump to Start: ${segment.start}`}
                                                        >
                                                            {segment.start}
                                                        </button>
                                                        <button
                                                            onClick={(e) => { e.stopPropagation(); onSeek(Math.max(0, parseTime(segment.start) - 1)); }}
                                                            className="px-2 py-1 rounded bg-slate-700 hover:bg-sky-600 text-slate-300 hover:text-white transition-colors"
                                                            title="Start - 1s"
                                                        >
                                                            -1s
                                                        </button>
                                                    </div>

                                                    {/* End Group */}
                                                    <div className="flex items-center gap-1 justify-end">
                                                        <button
                                                            onClick={(e) => { e.stopPropagation(); onSeek(Math.max(0, parseTime(segment.end) - 1)); }}
                                                            className="px-2 py-1 rounded bg-slate-700 hover:bg-indigo-600 text-slate-300 hover:text-white transition-colors"
                                                            title="End - 1s"
                                                        >
                                                            -1s
                                                        </button>
                                                        <button
                                                            onClick={(e) => { e.stopPropagation(); onSeek(parseTime(segment.end)); }}
                                                            className="px-2 py-1 rounded bg-indigo-500/10 border border-indigo-500/20 text-indigo-400 hover:bg-indigo-500 hover:text-white font-mono font-medium transition-colors"
                                                            title={`Jump to End: ${segment.end}`}
                                                        >
                                                            {segment.end}
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>

                                </div>
                            )}
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

window.FaceList = FaceList;
