/* global React, ChamberChrome */
const { useState, useEffect } = React;

function Feedback({ onBack }) {
  const moods = window.MOOD_OPTIONS || [];
  const [mood, setMood] = useState(null);
  const [text, setText] = useState("");
  const [name, setName] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const [recent, setRecent] = useState([]);

  // Load + persist
  useEffect(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("darshan.feedback") || "[]");
      setRecent(saved.slice(-12).reverse());
    } catch (e) {}
  }, []);

  const submit = () => {
    if (!mood || !text.trim()) return;
    const entry = {
      mood: mood.key,
      moodDev: mood.dev,
      moodEn: mood.en,
      text: text.trim(),
      name: name.trim() || "a traveller",
      at: new Date().toISOString(),
    };
    try {
      const all = JSON.parse(localStorage.getItem("darshan.feedback") || "[]");
      all.push(entry);
      localStorage.setItem("darshan.feedback", JSON.stringify(all));
      setRecent([entry, ...recent].slice(0, 12));
    } catch (e) {}
    setSubmitted(true);
  };

  if (submitted) {
    return (
      <div className="chamber chamber-feedback">
        <ChamberChrome onBack={onBack} num="vi." dev="प्रतिक्रिया" en="Feedback" />
        <div className="feedback-thanks">
          <div className="rule"></div>
          <div className="thanks-dev">धन्यवाद</div>
          <h1 className="thanks-title">your residue is kept.</h1>
          <p className="thanks-line">
            the archive has recorded a small, true {mood?.en?.toLowerCase()}. <br/>
            walk well, {name.trim() || "traveller"} —
          </p>
          <p className="thanks-foot">— rahul</p>
          <button className="chamber-link" onClick={() => { setSubmitted(false); setMood(null); setText(""); setName(""); }} data-cursor>
            ← leave another note
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="chamber chamber-feedback">
      <ChamberChrome onBack={onBack} num="vi." dev="प्रतिक्रिया" en="Feedback" />

      <header className="chamber-head">
        <h1 className="chamber-title">
          leave a small <em>residue.</em>
        </h1>
        <p className="chamber-sub">
          if a photograph moved you — even slightly — leave a word, a fragment, a single line. the archive listens.
        </p>
      </header>

      <div className="feedback-form">
        <div className="form-group">
          <div className="form-label">
            <span className="dev">भाव</span>
            choose the small feeling
          </div>
          <div className="mood-grid">
            {moods.map(m => (
              <button
                key={m.key}
                className={`mood-card ${mood?.key === m.key ? "active" : ""}`}
                onClick={() => setMood(m)}
                data-cursor
              >
                <span className="mood-dev">{m.dev}</span>
                <span className="mood-en">{m.en}</span>
                <span className="mood-line">— {m.line}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="form-group">
          <div className="form-label">
            <span className="dev">शब्द</span>
            write a line, a fragment, an unfinished sentence
          </div>
          <textarea
            className="form-area"
            placeholder="anything. one word is enough."
            value={text}
            onChange={e => setText(e.target.value)}
            rows={4}
            data-cursor
          ></textarea>
        </div>

        <div className="form-group">
          <div className="form-label">
            <span className="dev">नाम</span>
            and your name, if you wish to leave one
          </div>
          <input
            className="form-input"
            placeholder="a traveller"
            value={name}
            onChange={e => setName(e.target.value)}
            data-cursor
          />
        </div>

        <button
          className={`form-submit ${(!mood || !text.trim()) ? "disabled" : ""}`}
          onClick={submit}
          disabled={!mood || !text.trim()}
          data-cursor
        >
          <span className="dev">अर्पण</span>
          <span>offer the note</span>
          <span className="arrow">→</span>
        </button>
      </div>

      {recent.length > 0 && (
        <div className="recent-residue">
          <div className="rule"></div>
          <div className="recent-head">
            <span className="dev">पूर्व</span>
            small residues, left by other travellers
            <span className="quiet">(stored only on this device)</span>
          </div>
          <ul className="recent-list">
            {recent.slice(0, 6).map((r, i) => (
              <li key={i}>
                <div className="recent-mood">
                  <span className="dev">{r.moodDev}</span>
                  <span>{r.moodEn}</span>
                </div>
                <div className="recent-text">"{r.text}"</div>
                <div className="recent-meta">— {r.name}</div>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}

window.Feedback = Feedback;
