// AI photo staging — before/after (phase 1, 2026-08-29; launch guardrails
// 2026-10-28). Opened from the "AI Stage" button on a listing photo. Flow:
// pick the room type (the guardrail — a person can see what the room is, the
// model has to guess) → Generate ONE candidate → shown beside the original
// with the per-run cost → exactly two ways out: Keep (saves a NEW attachment
// marked staged — the original is never touched) or Discard (server forgets
// the candidate; nothing was written to the gallery).
// `rooms` = the pick-only vocabulary from GET /api/staging/status.
const StagingModal = ({ propertyId, photo, rooms = [], onKept, onClose }) => {
    const [state, setState]   = React.useState('pick');   // pick | working | ready | saving | error
    const [room, setRoom]     = React.useState('');   // nothing picked until the person names the room
    const [originalUrl, setOriginalUrl] = React.useState(null);
    React.useEffect(() => {
        let u = null;
        api.attachmentImageUrl(photo.id).then(x => { u = x; setOriginalUrl(x); }).catch(() => {});
        return () => { if (u) URL.revokeObjectURL(u); };
    }, [photo.id]);
    const [result, setResult] = React.useState(null);
    const [error, setError]   = React.useState(null);

    const generate = async () => {
        setState('working'); setError(null);
        try { const r = await api.stagePhoto(propertyId, photo.id, room); setResult(r); setState('ready'); }
        catch (e) { setError(e.message); setState('error'); }
    };
    const keep = async () => {
        setState('saving');
        try { await api.keepStaging(result.run_id); onKept(); }
        catch (e) { setError('Could not save: ' + e.message); setState('ready'); }
    };
    const discard = async () => {
        if (result) { try { await api.discardStaging(result.run_id); } catch { /* expired = already gone */ } }
        onClose();
    };
    const money = (n) => n == null ? '—' : `$${Number(n).toFixed(4)}`;
    const roomLabel = rooms.find(r => r.key === room)?.label || room;
    const decorOnly = ['kitchen', 'bathroom', 'entry', 'utility', 'closet'].includes(room);

    return (
        <div className="modal-overlay" onClick={state === 'working' ? undefined : discard}>
            <div className="modal" style={{ maxWidth: '64rem' }} onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                    <h2><i className="fas fa-wand-magic-sparkles"></i> AI photo staging</h2>
                    {state !== 'working' && <button className="modal-close" onClick={discard}>&times;</button>}
                </div>
                <div className="modal-body">
                    {state === 'pick' && (
                        <div className="form-group" style={{ marginBottom: '0.75rem' }}>
                            <label htmlFor="staging-room">What room is this?</label>
                            <select id="staging-room" value={room} onChange={e => setRoom(e.target.value)}>
                                <option value="" disabled>Pick the room…</option>
                                {rooms.map(r => <option key={r.key} value={r.key}>{r.label}</option>)}
                            </select>
                            <p style={{ fontSize: '0.8125rem', color: 'var(--text-2)', margin: '0.375rem 0 0' }}>
                                {decorOnly
                                    ? <>Decor only for this kind of room — no furniture is added, shelving and fixtures stay. Doorways, walkways and stairs stay clear.</>
                                    : <>Name the room: it tells the tool what belongs there and what never does (no table in a kitchen, no bed in a closet, nothing across a doorway). "Not sure" lets it guess — it guessed a closet was a bedroom once.</>}
                            </p>
                        </div>
                    )}
                    <div className="staging-compare">
                        <figure>
                            {originalUrl ? <img src={originalUrl} alt="Original" /> : <div className="photo-placeholder" />}
                            <figcaption>Before — {photo.caption || photo.original_name}</figcaption>
                        </figure>
                        <figure>
                            {result
                                ? <img src={result.preview} alt="Virtually staged candidate" />
                                : <div style={{ aspectRatio: '4 / 3', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-3)', border: '1px dashed var(--border)', borderRadius: '0.5rem' }}>
                                    {state === 'error' ? <span style={{ color: 'var(--danger, #ef4444)', padding: '1rem', textAlign: 'center' }}>{error}</span>
                                     : state === 'pick' ? <span style={{ padding: '1rem', textAlign: 'center' }}>Pick the room, then Generate</span>
                                     : <span><i className="fas fa-spinner fa-spin"></i> Staging… this takes 30–90 seconds</span>}
                                  </div>}
                            <figcaption>After — virtually staged{result ? ` (${roomLabel}, not saved yet)` : ''}</figcaption>
                        </figure>
                    </div>
                    {result && (
                        <p style={{ fontSize: '0.8125rem', color: 'var(--text-2)', marginTop: '0.75rem' }}>
                            <strong>This run cost {money(result.cost_usd)}</strong>
                            {' '}· {result.model} · {result.quality} · {result.size}
                            {result.usage && <> · {result.usage.input_tokens} in / {result.usage.output_tokens} out tokens</>}
                            {' '}· {(result.duration_ms / 1000).toFixed(0)}s · run {result.used_today} of {result.cap_per_day} today.
                            <span style={{ color: 'var(--text-3)' }}> Our arithmetic from the provider's token counts — reconcile against the OpenAI console.</span>
                        </p>
                    )}
                    {result && (
                        <p style={{ fontSize: '0.8125rem', color: '#b45309', marginTop: '0.5rem' }}>
                            <i className="fas fa-triangle-exclamation"></i> <strong>Check before you keep:</strong> same windows, doors, ceiling fan and fixtures, ceiling shape, flooring and framing as the original? Every doorway and walkway still clear, nothing across a door or on the stairs, closet shelving still there, no furniture in a kitchen, bath or closet? The tool must add furniture only — a changed room misleads buyers and "virtually staged" does not cover it. If it got it wrong, Discard — a discarded run is never shown anywhere. Keep puts the staged photo in the original's place (same spot, in the app and on the website); the original is kept and comes back if you delete the staged one.
                            {result.aspect_note && <> {result.aspect_note}</>}
                        </p>
                    )}
                    {state === 'ready' && error && <p style={{ color: 'var(--danger, #ef4444)', fontSize: '0.8125rem' }}>{error}</p>}
                {/* Inside .modal-body on purpose: outside it there is no padding and the
                    modal's overflow clip cut the Keep label down to its icon (seen live). */}
                <div className="modal-actions" style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', justifyContent: 'flex-end', marginTop: '1rem' }}>
                    <button type="button" className="btn btn-secondary" onClick={discard} disabled={state === 'working' || state === 'saving'}>
                        {state === 'error' || state === 'pick' ? 'Cancel' : 'Discard'}
                    </button>
                    {state === 'pick' || state === 'error'
                        ? <button type="button" className="btn btn-primary" onClick={generate} disabled={!room}>
                              <i className="fas fa-wand-magic-sparkles"></i> {state === 'error' ? 'Try again' : 'Generate'}
                          </button>
                        : <button type="button" className="btn btn-primary" onClick={keep} disabled={state !== 'ready'}>
                              {state === 'saving' ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-check"></i> Keep — replace the original</>}
                          </button>}
                </div>
                </div>
            </div>
        </div>
    );
};
