// Settings → Open Hours — the weekly schedule + days the business is closed.
//
// The website reads this from the public feed (with a server-computed
// open_now), so the owner changes their own hours instead of asking us
// (HQ ask, 2026-08-27 — Doug's Point). Kept deliberately plain: seven rows,
// an Open/Closed chip pair per day, time pickers, "+ split" for a second
// range, holiday chips (no checkbox lists — standing rule) and a date field
// for one-off closures. Server: PUT /api/tenant { hours } → lib/hours.js,
// which owns validation; this form only keeps the shape tidy.

const HOURS_DAYS = [['mon', 'Monday'], ['tue', 'Tuesday'], ['wed', 'Wednesday'], ['thu', 'Thursday'],
                    ['fri', 'Friday'], ['sat', 'Saturday'], ['sun', 'Sunday']];
// Mirrors HOLIDAYS in server/lib/hours.js (keys must match — the server
// refuses anything else). Order = the order the chips render.
const HOURS_HOLIDAYS = [['new-years', "New Year's Day"], ['easter', 'Easter Sunday'], ['memorial-day', 'Memorial Day'],
                        ['july-4', 'Independence Day'], ['labor-day', 'Labor Day'], ['thanksgiving', 'Thanksgiving'],
                        ['christmas-eve', 'Christmas Eve'], ['christmas', 'Christmas Day'], ['new-years-eve', "New Year's Eve"]];
// Short list first; the full IANA list sits under "Other" so nobody scrolls
// past 400 zones to find New York.
const HOURS_US_ZONES = [['America/New_York', 'Eastern'], ['America/Chicago', 'Central'], ['America/Denver', 'Mountain'],
                        ['America/Phoenix', 'Arizona (no DST)'], ['America/Los_Angeles', 'Pacific'], ['America/Anchorage', 'Alaska'],
                        ['Pacific/Honolulu', 'Hawaii']];

const HoursSection = ({ tenant, onTenantChange }) => {
    const empty = { timezone: 'America/New_York', days: {}, holidays: [], closed_dates: [], note: '' };
    const cur = (tenant && tenant.hours) || null;
    const seed = () => cur ? { ...empty, ...cur, note: cur.note || '' } : { ...empty };
    const [form, setForm]     = React.useState(seed);
    const [newDate, setNewDate] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const [error, setError]   = React.useState('');
    const [saved, setSaved]   = React.useState(false);

    // Canonical serialization for the dirty check — the server returns days
    // in sun..sat order while the form builds them in edit order.
    const canon = (h) => h && JSON.stringify({
        timezone: h.timezone, days: Object.fromEntries(['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].map(k => [k, h.days[k] || []])),
        holidays: [...(h.holidays || [])].sort(), closed_dates: [...(h.closed_dates || [])].sort(), note: (h.note || '').trim() || null });
    const dirty = canon({ ...empty, ...form }) !== canon(cur);
    const ranges = (k) => form.days[k] || [];
    const setDay = (k, r) => setForm(f => ({ ...f, days: { ...f.days, [k]: r } }));
    const setRange = (k, i, pos, val) => setDay(k, ranges(k).map((r, x) => x === i ? (pos === 0 ? [val, r[1]] : [r[0], val]) : r));
    const addSplit = (k) => { const r = ranges(k); const last = r[r.length - 1]; setDay(k, [...r, [last ? last[1] : '17:00', '21:00']]); };
    const removeRange = (k, i) => setDay(k, ranges(k).filter((_, x) => x !== i));
    const toggleOpen = (k, on) => setDay(k, on ? (ranges(k).length ? ranges(k) : [['09:00', '17:00']]) : []);
    // "Same as Monday" — the common case is one schedule Mon–Fri; copying
    // is faster than typing it five times.
    const copyToWeekdays = (from) => setForm(f => {
        const days = { ...f.days };
        for (const [k] of HOURS_DAYS.slice(0, 5)) days[k] = (f.days[from] || []).map(r => [...r]);
        return { ...f, days };
    });
    const toggleHoliday = (key) => setForm(f => ({ ...f, holidays: f.holidays.includes(key) ? f.holidays.filter(h => h !== key) : [...f.holidays, key] }));
    const addDate = (e) => {
        e.preventDefault();
        if (!newDate) return;
        if (form.closed_dates.includes(newDate)) { setError('That date is already on the list.'); return; }
        setForm(f => ({ ...f, closed_dates: [...f.closed_dates, newDate].sort() })); setNewDate(''); setError('');
    };

    const save = async () => {
        setSaving(true); setError(''); setSaved(false);
        try {
            const updated = await api.updateTenant({ hours: { ...form, note: form.note.trim() || null } });
            onTenantChange && onTenantChange(updated);
            setSaved(true);
        } catch (err) { setError(err.message); }
        finally { setSaving(false); }
    };

    const chip = (on) => on ? { background: 'var(--accent, #3b82f6)', color: '#fff' } : {};
    const prettyDate = (ymd) => new Date(ymd + 'T12:00:00').toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
    const allZones = (typeof Intl.supportedValuesOf === 'function') ? Intl.supportedValuesOf('timeZone') : [];
    const usKeys = HOURS_US_ZONES.map(z => z[0]);

    return (
        <div className="settings-section">
            {error && <div className="api-error">{error}</div>}
            {saved && !dirty && <div className="api-success">Saved. Your website picks up the change within a few minutes.</div>}

            {/* ── Weekly hours ── */}
            <div className="form-group">
                <label className="form-label">Weekly hours</label>
                <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', margin: '0 0 0.5rem' }}>
                    A closing time earlier than the opening time means past midnight (4:00 PM – 2:00 AM).
                </p>
                <table className="data-table hours-table" style={{ maxWidth: 640 }}>
                    <tbody>
                        {HOURS_DAYS.map(([k, label]) => {
                            const open = ranges(k).length > 0;
                            return (
                                <tr key={k}>
                                    <td style={{ width: 110, fontWeight: 500 }}>{label}</td>
                                    <td style={{ width: 160 }}>
                                        <div className="tag-filter-row" style={{ margin: 0, flexWrap: 'nowrap' }}>
                                            <span className="tag-pill tag-filter-chip" style={chip(open)} onClick={() => toggleOpen(k, true)}>Open</span>
                                            <span className="tag-pill tag-filter-chip" style={chip(!open)} onClick={() => toggleOpen(k, false)}>Closed</span>
                                        </div>
                                    </td>
                                    <td>
                                        {open && ranges(k).map((r, i) => (
                                            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', marginBottom: i < ranges(k).length - 1 ? '0.35rem' : 0 }}>
                                                <input type="time" className="form-input" style={{ width: 132 }} value={r[0]} onChange={e => setRange(k, i, 0, e.target.value)} />
                                                <span style={{ color: 'var(--text-3)' }}>to</span>
                                                <input type="time" className="form-input" style={{ width: 132 }} value={r[1]} onChange={e => setRange(k, i, 1, e.target.value)} />
                                                {ranges(k).length > 1 && (
                                                    <button type="button" className="btn-icon-sm danger" title="Remove this range" onClick={() => removeRange(k, i)}><i className="fas fa-times"></i></button>
                                                )}
                                                {i === ranges(k).length - 1 && ranges(k).length < 2 && (
                                                    <button type="button" className="btn-link" style={{ fontSize: '0.75rem', whiteSpace: 'nowrap' }} title="Add a second range — e.g. lunch and dinner" onClick={() => addSplit(k)}>+ split</button>
                                                )}
                                            </div>
                                        ))}
                                    </td>
                                    <td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
                                        {k === 'mon' && open && (
                                            <button type="button" className="btn-link" style={{ fontSize: '0.75rem' }} onClick={() => copyToWeekdays('mon')}>Copy to Tue–Fri</button>
                                        )}
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </div>

            <div className="form-group" style={{ maxWidth: 420 }}>
                <label className="form-label">Time zone</label>
                <select className="form-input" value={form.timezone} onChange={e => setForm(f => ({ ...f, timezone: e.target.value }))}>
                    <optgroup label="United States">
                        {HOURS_US_ZONES.map(([tz, label]) => <option key={tz} value={tz}>{label} — {tz}</option>)}
                    </optgroup>
                    {allZones.length > 0 && (
                        <optgroup label="Other">
                            {allZones.filter(tz => !usKeys.includes(tz)).map(tz => <option key={tz} value={tz}>{tz}</option>)}
                        </optgroup>
                    )}
                </select>
            </div>

            {/* ── Closed these days ── */}
            <div className="form-group">
                <label className="form-label">Closed these days</label>
                <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', margin: '0 0 0.5rem' }}>
                    Tap a holiday to close every year on that day. Add any other date below.
                </p>
                <div className="tag-filter-row">
                    {HOURS_HOLIDAYS.map(([key, label]) => (
                        <span key={key} className="tag-pill tag-filter-chip" style={chip(form.holidays.includes(key))} onClick={() => toggleHoliday(key)}>
                            {form.holidays.includes(key) && <i className="fas fa-check" style={{ marginRight: '0.3rem' }}></i>}{label}
                        </span>
                    ))}
                </div>
                {form.closed_dates.length > 0 && (
                    <div className="tag-filter-row" style={{ marginTop: '0.5rem' }}>
                        {form.closed_dates.map(d => (
                            <span key={d} className="tag-pill" title="Closed on this date only">
                                <i className="fas fa-calendar-times" style={{ marginRight: '0.3rem', opacity: 0.7 }}></i>{prettyDate(d)}
                                <button type="button" className="btn-icon-sm danger" style={{ marginLeft: '0.2rem', padding: '0 0.2rem' }} title="Remove"
                                        onClick={() => setForm(f => ({ ...f, closed_dates: f.closed_dates.filter(x => x !== d) }))}><i className="fas fa-times"></i></button>
                            </span>
                        ))}
                    </div>
                )}
                <form onSubmit={addDate} style={{ display: 'flex', gap: '0.5rem', maxWidth: 360, marginTop: '0.5rem' }}>
                    <input type="date" className="form-input" value={newDate} onChange={e => setNewDate(e.target.value)} />
                    <button type="submit" className="btn btn-secondary btn-small" disabled={!newDate}><i className="fas fa-plus"></i> Add a date</button>
                </form>
            </div>

            <div className="form-group" style={{ maxWidth: 640 }}>
                <label className="form-label">Note <span style={{ fontWeight: 400, color: 'var(--text-3)' }}>(optional, shown on your website)</span></label>
                <input className="form-input" value={form.note} maxLength={200} onChange={e => setForm(f => ({ ...f, note: e.target.value }))}
                       placeholder="e.g. Kitchen closes 30 minutes before close" />
            </div>

            <div className="btn-group">
                <button type="button" className="btn btn-primary" disabled={saving || !dirty} onClick={save}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-check"></i> Save</>}
                </button>
            </div>
        </div>
    );
};
