// shared.jsx -- reusable bits: Reveal, Card, InquiryForm

// Fade-up on scroll -- visible by default; animation is progressive enhancement
const Reveal = ({ children, delay=0, tag='div', className='', style={} }) => {
  const ref = React.useRef(null);
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) { setSeen(true); return; }
    // Already on screen at mount → show immediately (no hidden flash).
    if (el.getBoundingClientRect().top < window.innerHeight * 0.95) setSeen(true);
    let io;
    if ('IntersectionObserver' in window) {
      io = new IntersectionObserver(([e]) => {
        if (e.isIntersecting) { setSeen(true); io.disconnect(); }
      }, { threshold:0.12, rootMargin:'0px 0px -8% 0px' });
      io.observe(el);
    }
    // Safety net: never leave content hidden if the observer can't fire.
    const fallback = setTimeout(() => setSeen(true), 500);
    return () => { if (io) io.disconnect(); clearTimeout(fallback); };
  }, []);
  const Tag = tag;
  return (
    <Tag ref={ref} className={"fade-up " + (seen ? "in " : "") + className}
         style={{ animationDelay:(seen ? delay : 0) + 'ms', ...style }}>
      {children}
    </Tag>
  );
};

// Painting card (image or placeholder)
const Card = ({ work, onOpen }) => {
  const sold = work.status === 'sold';
  return (
    <div className="card" onClick={() => onOpen(work)}>
      <div className="imgwrap" style={{'--ar': work.ar || '4/5'}}>
        {sold && <div className="badge">Sold</div>}
        {work.img
          ? <img src={work.img} alt={work.title} loading="lazy" />
          : <div className="ph">
              <div className="phn">{window.seriesById(work.series)?.title}</div>
              <div className="pht">{work.title}</div>
              <div className="phn">Not pictured · inquire</div>
            </div>}
      </div>
      <div className="cap">
        <div className="ct">{work.title}</div>
        <div className="cm">{work.medium}</div>
        <div className="cmeta">
          <span className="csize">{work.size} · {work.year}</span>
          <span className={"cprice" + (sold ? " sold" : "")}>{window.fmtPrice(work)}</span>
        </div>
      </div>
    </div>
  );
};

// Collector inquiry form (used on Collect page + modal CTA target)
const InquiryForm = ({ presetWork, light=false }) => {
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const [form, setForm] = React.useState({
    name:'', email:'',
    message: presetWork ? `I'd like to inquire about "${presetWork.title}."\n` : ''
  });
  const set = (k) => (e) => setForm(f => ({...f, [k]:e.target.value}));
  const cls = "field" + (light ? " light" : "");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch('/api/inquiry', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          message: form.message,
          workTitle: presetWork?.title,
        }),
      });
      if (!res.ok) throw new Error('Send failed');
      setSent(true);
    } catch {
      setError('Something went wrong -- please email the studio directly.');
    } finally {
      setSubmitting(false);
    }
  };

  if (sent) return (
    <div style={{display:'flex', flexDirection:'column', gap:14}}>
      <span className="flare-dot"></span>
      <div className={"lead" + (light ? "" : " on-dark")}>
        Message received. Drury will reply personally -- usually within a day or two.
      </div>
      <p className={"meta" + (light ? "" : " on-dark")}>
        No deposit, no pressure. We'll talk through the piece, framing, and shipping before anything is decided.
      </p>
    </div>
  );

  return (
    <form style={{display:'flex', flexDirection:'column', gap:18}} onSubmit={handleSubmit}>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16}}>
        <div className={cls}>
          <label>Name</label>
          <input required value={form.name} onChange={set('name')} />
        </div>
        <div className={cls}>
          <label>Email</label>
          <input required type="email" value={form.email} onChange={set('email')} />
        </div>
      </div>
      <div className={cls}>
        <label>{presetWork ? 'Your inquiry' : 'How can the studio help?'}</label>
        <textarea rows={presetWork ? 4 : 5} value={form.message} onChange={set('message')} />
      </div>
      {error && <p style={{color:'var(--flare)', fontSize:13, margin:0}}>{error}</p>}
      <button type="submit" disabled={submitting}
              className={"btn " + (light ? "btn-ink" : "btn-veil")}
              style={{alignSelf:'flex-start', opacity: submitting ? 0.6 : 1}}>
        {submitting ? 'Sending…' : 'Send to the studio →'}
      </button>
    </form>
  );
};

Object.assign(window, { Reveal, Card, InquiryForm });
