import React from 'react';
import { STATUS_CONFIG, formatDate, getDDays } from '../realEstateUtils';

// ── 청약 일정 타임라인 ─────────────────────────────────────────────────────────
const ScheduleView = ({ complexes }) => {
    const events = complexes
        .filter((c) => c.subscriptionStart)
        .flatMap((c) => [
            { date: c.subscriptionStart, label: '청약 시작', complex: c, type: 'start' },
            { date: c.subscriptionEnd, label: '청약 마감', complex: c, type: 'end' },
            { date: c.resultDate, label: '당첨 발표', complex: c, type: 'result' },
        ])
        .filter((e) => e.date)
        .sort((a, b) => new Date(a.date) - new Date(b.date));

    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const upcoming = events.filter((e) => new Date(e.date) >= today);
    const past = events.filter((e) => new Date(e.date) < today).reverse();

    const EventItem = ({ event }) => {
        const cfg = STATUS_CONFIG[event.complex.status] || STATUS_CONFIG['완료'];
        const dday = getDDays(event.date);
        return (
            <div className={`re-schedule-item re-schedule-item--${event.type}`}>
                <div className="re-schedule-item__date">
                    <span className="re-schedule-item__dday" style={{ color: cfg.color }}>{dday}</span>
                    <span className="re-schedule-item__datestr">{formatDate(event.date)}</span>
                </div>
                <div className="re-schedule-item__dot" style={{ background: cfg.color, boxShadow: `0 0 6px ${cfg.color}` }} />
                <div className="re-schedule-item__content">
                    <p className="re-schedule-item__complex">{event.complex.name}</p>
                    <p className="re-schedule-item__label">{event.label}</p>
                </div>
            </div>
        );
    };

    return (
        <div className="re-schedule">
            {upcoming.length > 0 && (
                <div className="re-schedule-section">
                    <h4 className="re-schedule-section__title">예정 일정</h4>
                    {upcoming.map((e, i) => <EventItem key={i} event={e} />)}
                </div>
            )}
            {past.length > 0 && (
                <div className="re-schedule-section">
                    <h4 className="re-schedule-section__title re-schedule-section__title--past">지난 일정</h4>
                    {past.map((e, i) => <EventItem key={i} event={e} />)}
                </div>
            )}
            {events.length === 0 && <p className="re-empty">등록된 청약 일정이 없습니다.</p>}
        </div>
    );
};

export default ScheduleView;
