/* Compatibility and model requests */

const Compatibility = () => {
  const { t } = useLang();
  const openRequests = (CFG.futureDevices || []).filter((device) => device.status === 'request_open');
  return (
    <>
      <PageHero eyebrow={t.compatibility.eyebrow} title={t.compatibility.title} sub={t.compatibility.sub} />
      <section className="section-tight">
        <div className="container stack" style={{ gap: 32 }}>
          <div>
            <div className="eyebrow">{t.compatibility.liveTitle}</div>
            <div className="grid cols-3" style={{ marginTop: 16 }}>
              {getLiveDevices().map((device) => (
                <DeviceCard key={device.id} device={device} live />
              ))}
            </div>
          </div>

          <div>
            <div className="eyebrow">{t.compatibility.futureTitle}</div>
            <div className="grid cols-3" style={{ marginTop: 16 }}>
              {openRequests.length ? openRequests.map((device) => (
                <ModelWaitlistCard key={device.id} device={device} />
              )) : (
                <div className="surface-plain stack" style={{ padding: 20 }}>
                  <h3 className="h-3">{t.compatibility.noOpenModelsTitle}</h3>
                  <p className="body-muted">{t.compatibility.noOpenModelsBody}</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
      <RequestModelSection />
    </>
  );
};

const DeviceCard = ({ device, live }) => {
  const { t } = useLang();
  const progress = live
    ? 100
    : Math.min(100, Math.round((device.requestCount / device.requestThreshold) * 100));
  const statusMap = {
    request_open: t.compatibility.requestOpen,
    in_design: t.compatibility.inDesign,
    test_fit: t.compatibility.testFit,
    production_ready: t.compatibility.productionReady,
    live: t.compatibility.live
  };
  return (
    <article className="surface-plain stack" style={{ padding: 20 }}>
      <div className="row-between">
        <span className="tag tag-dot">{live ? (device.shortName || t.compatibility.live) : (statusMap[device.status] || t.compatibility.requestOpen)}</span>
        {device.sku && <span className="mono-sm">{device.sku}</span>}
      </div>
      <h3 className="h-3">{live ? (device.fullName || device.displayName) : device.displayName}</h3>
      {live ? (
        <p className="body-muted">{t.product.designedFor.replace('{device}', device.displayName)}</p>
      ) : (
        <>
          <div className="progress" aria-hidden="true"><span style={{ '--progress': progress + '%' }}></span></div>
          <p className="mono-sm">
            {t.compatibility.progress
              .replace('{count}', device.requestCount)
              .replace('{threshold}', device.requestThreshold)}
          </p>
        </>
      )}
    </article>
  );
};

const ModelWaitlistCard = ({ device }) => {
  const { t, lang } = useLang();
  const [open, setOpen] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [privacyConsent, setPrivacyConsent] = React.useState(false);
  const [website, setWebsite] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const count = Number(device.requestCount || 0);
  const target = Number(device.requestThreshold || 50);
  const progress = Math.min(100, Math.round((count / target) * 100));

  const submit = async (event) => {
    event.preventDefault();
    if (loading) return;
    const emailKey = String(email || '').trim().toLowerCase();
    const localKey = `tc_model_waitlist_${device.id}_${emailKey}`;
    try {
      if (localStorage.getItem(localKey)) {
        setDone(true);
        return;
      }
    } catch (e) {}

    setLoading(true);
    setError('');
    const result = await submitRecord('/api/model-request', {
      action: 'join_model_waitlist',
      modelId: device.id,
      brand: device.brand || '',
      model: device.displayName,
      email,
      privacyConsent,
      language: lang,
      sourcePage: 'compatibility',
      website
    });
    setLoading(false);
    if (result.ok) {
      try { localStorage.setItem(localKey, '1'); } catch (e) {}
      setDone(true);
    } else {
      setError(result.error || t.common.requestFailed);
    }
  };

  return (
    <article className="surface-plain stack" style={{ padding: 20 }}>
      <div className="row-between">
        <span className="tag tag-dot">{t.compatibility.requestOpen}</span>
        <span className="mono-sm">{count}</span>
      </div>
      <h3 className="h-3">{device.displayName}</h3>
      <div className="progress" aria-hidden="true"><span style={{ '--progress': progress + '%' }}></span></div>
      <p className="mono-sm">
        {t.compatibility.progress
          .replace('{count}', count)
          .replace('{threshold}', target)}
      </p>

      {!open && !done && (
        <button type="button" className="btn btn-secondary btn-arrow" onClick={() => setOpen(true)}>
          {t.compatibility.joinWaitlist}
        </button>
      )}

      {open && !done && (
        <form className="stack" style={{ gap: 12 }} onSubmit={submit}>
          <Field label={t.compatibility.email}>
            <input className="input" type="email" required value={email} onChange={(event) => setEmail(event.target.value)} />
          </Field>
          <CheckLabel
            checked={privacyConsent}
            onChange={setPrivacyConsent}
            text={t.compatibility.privacyConsent}
            required
          />
          <input
            type="text"
            value={website}
            onChange={(event) => setWebsite(event.target.value)}
            tabIndex="-1"
            autoComplete="off"
            className="hp-field"
            aria-hidden="true"
          />
          <button className="btn btn-primary btn-block btn-arrow" type="submit" disabled={loading}>
            {loading ? '...' : t.compatibility.joinWaitlist}
          </button>
          {error && <p className="notice notice-danger" role="alert">{error}</p>}
        </form>
      )}

      {done && <p className="notice" role="status">{t.compatibility.waitlistJoined}</p>}
    </article>
  );
};

const RequestModelSection = () => {
  const { t, lang } = useLang();
  const [form, setForm] = React.useState({ brand: '', model: '', email: '', notes: '', photo: '', privacyConsent: false, website: '' });
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const set = (patch) => setForm((current) => ({ ...current, ...patch }));

  const submit = async (event) => {
    event.preventDefault();
    if (loading) return;
    setLoading(true);
    setError('');
    setSent(false);
    const result = await submitRecord('/api/model-request', {
      ...form,
      action: 'request_new_model',
      language: lang,
      sourcePage: 'compatibility'
    });
    setLoading(false);
    if (result.ok) {
      setSent(true);
      setForm({ brand: '', model: '', email: '', notes: '', photo: '', privacyConsent: false, website: '' });
    } else {
      setError(result.error || t.common.requestFailed);
    }
  };

  return (
    <section className="section band">
      <div className="container contact-grid">
        <div className="stack" style={{ gap: 18 }}>
          <div className="eyebrow">{t.compatibility.formTitle}</div>
          <h2 className="h-1">{t.home.compatibility.request}</h2>
          <p className="lead">{t.compatibility.requestHelp}</p>
        </div>
        <form className="surface stack" style={{ padding: 22 }} onSubmit={submit}>
          {sent && <p className="notice" role="status">{t.compatibility.sent}</p>}
          {error && <p className="notice notice-danger" role="alert">{error}</p>}
          <div className="grid cols-2">
            <Field label={t.compatibility.brand}>
              <input className="input" required value={form.brand} onChange={(event) => set({ brand: event.target.value })} />
            </Field>
            <Field label={t.compatibility.model}>
              <input className="input" required value={form.model} onChange={(event) => set({ model: event.target.value })} />
            </Field>
          </div>
          <Field label={t.compatibility.photo}>
            <label className="choice">
              <input
                type="file"
                hidden
                onChange={(event) => set({ photo: event.target.files && event.target.files[0] ? event.target.files[0].name : '' })}
              />
              <span>{form.photo || t.compatibility.photoPlaceholder}</span>
            </label>
          </Field>
          <Field label={t.compatibility.email}>
            <input className="input" type="email" required value={form.email} onChange={(event) => set({ email: event.target.value })} />
          </Field>
          <Field label={t.compatibility.notes}>
            <textarea className="textarea" value={form.notes} onChange={(event) => set({ notes: event.target.value })}></textarea>
          </Field>
          <CheckLabel
            checked={form.privacyConsent}
            onChange={(value) => set({ privacyConsent: value })}
            text={t.compatibility.privacyConsent}
            required
          />
          <input
            type="text"
            value={form.website}
            onChange={(event) => set({ website: event.target.value })}
            tabIndex="-1"
            autoComplete="off"
            className="hp-field"
            aria-hidden="true"
          />
          <button className="btn btn-primary btn-block btn-arrow" type="submit" disabled={loading}>
            {loading ? '...' : t.compatibility.button}
          </button>
        </form>
      </div>
    </section>
  );
};

window.Compatibility = Compatibility;
