import { useState, useRef } from 'react';

const Contact = () => {
    const [formData, setFormData] = useState({
        name: '',
        phone: '',
        message: '',
        honeypot: '' // Hidden field for spam bots
    });
    const [status, setStatus] = useState('');
    const startTime = useRef(Date.now());

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        // 1. Honeypot Check
        if (formData.honeypot) {
            console.log('Spam bot detected (honeypot filled)');
            return;
        }

        setStatus('전송 중...');

        try {
            const response = await fetch("https://formsubmit.co/ajax/contact@qideun.com", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json"
                },
                body: JSON.stringify({
                    name: formData.name,
                    phone: formData.phone,
                    message: formData.message,
                    _subject: `[Sokuree] 새로운 문의가 도착했습니다: ${formData.name}님`
                })
            });

            if (response.ok) {
                setStatus('문의가 성공적으로 접수되었습니다! 담당자가 곧 연락드리겠습니다.');
                setFormData({ name: '', phone: '', message: '', honeypot: '' });
                alert('문의가 접수되었습니다. 확인 후 연락드리겠습니다!');
            } else {
                setStatus('전송에 실패했습니다. 잠시 후 다시 시도해주세요.');
            }
        } catch (error) {
            console.error('Error:', error);
            setStatus('오류가 발생했습니다. 직접 이메일로 연락 부탁드립니다.');
        }
    };

    return (
        <section id="contact" className="section-padding bg-light">
            <div className="container">
                <h2 className="section-title">문의하기</h2>
                <p className="section-subtitle" style={{ textAlign: 'center' }}>도입 상담부터 견적 문의까지 친절하게 안내해 드립니다.</p>

                <form className="contact-form" onSubmit={handleSubmit}>
                    {/* Honeypot Field - Hidden with CSS */}
                    <div style={{ display: 'none' }}>
                        <label htmlFor="honeypot">Leave this field blank</label>
                        <input
                            type="text"
                            name="honeypot"
                            id="honeypot"
                            value={formData.honeypot}
                            onChange={handleChange}
                            tabIndex="-1"
                            autoComplete="off"
                        />
                    </div>

                    <div className="form-group">
                        <label htmlFor="name">담당자명</label>
                        <input
                            type="text"
                            id="name"
                            name="name"
                            required
                            value={formData.name}
                            onChange={handleChange}
                            placeholder="홍길동"
                        />
                    </div>

                    <div className="form-group">
                        <label htmlFor="phone">연락처</label>
                        <input
                            type="tel"
                            id="phone"
                            name="phone"
                            required
                            value={formData.phone}
                            onChange={handleChange}
                            placeholder="010-1234-5678"
                        />
                    </div>

                    <div className="form-group">
                        <label htmlFor="message">문의 내용</label>
                        <textarea
                            id="message"
                            name="message"
                            required
                            value={formData.message}
                            onChange={handleChange}
                            placeholder="업종, 필요 품목 등 상세 내용을 적어주세요."
                            rows="5"
                        ></textarea>
                    </div>

                    <button type="submit" className="btn btn-primary">상담 신청하기</button>

                    {status && <p className="form-status">{status}</p>}
                </form>
            </div>
        </section>
    );
};

export default Contact;
