// The mobile cleaner form. Driven by store.cleanerFormFields so admins can
// reorder/add fields in Portal Settings and the live preview updates.
function CleanerMobileForm({ store, embedded = false }) {
  const fields = store.cleanerFormFields || DEFAULT_CLEANER_FIELDS;
  const buildInitial = () => {
    const init = {};
    fields.forEach(f => {
      if (f.id === 'date') init.date = '2026-04-24';
      else if (f.id === 'houseId') init.houseId = store.houses[0].id;
      else if (f.kind === 'checklist') init[f.id] = [];
      else if (f.kind === 'yesno') init[f.id] = null;
      else init[f.id] = '';
    });
    return init;
  };
  const [form, setForm] = React.useState(buildInitial);
  const [hasReceipt, setHasReceipt] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);

  // Reset when fields change (live preview from Portal Settings)
  const fieldsKey = fields.map(f => f.id).join('|');
  React.useEffect(() => { setForm(buildInitial()); }, [fieldsKey]);

  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const house = store.houses.find(h => h.id === form.houseId) || store.houses[0];

  const isValid = fields.every(f => {
    if (!f.required) return true;
    const v = form[f.id];
    if (f.kind === 'photo') return f.id === 'laundryReceipt' ? hasReceipt || !fields.find(ff => ff.id === 'laundryAmount')?.required : true;
    if (f.kind === 'yesno') return v !== null;
    if (f.kind === 'checklist') return true; // optional even if required
    return v !== '' && v != null;
  });

  const submit = () => {
    const laundryAmount = Number(form.laundryAmount) || 0;
    store.addCleaning({
      date: form.date,
      houseId: form.houseId,
      cleaner: 'Maria Delgado',
      laundryAmount,
      laundryReceiptUrl: hasReceipt ? 'receipt' : null,
      notes: form.notes || '',
      extras: Object.fromEntries(
        fields
          .filter(f => !f.system && !['laundryAmount','laundryReceipt','notes'].includes(f.id))
          .map(f => [f.id, { label: f.label, value: form[f.id] }])
      ),
    }, house);
    setSubmitted(true);
  };

  const reset = () => {
    setSubmitted(false);
    setForm(buildInitial());
    setHasReceipt(false);
  };

  const bg = '#f5f3ee';
  const cardBg = '#fff';

  if (submitted) {
    return (
      <div style={{
        height: '100%', background: bg, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', padding: 24, textAlign: 'center', fontFamily: 'Inter, system-ui',
      }}>
        <div style={{ width: 72, height: 72, borderRadius: '50%', background: '#2d5f3f', color: 'white',
          display: 'grid', placeItems: 'center', marginBottom: 20 }}>
          <svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12l5 5 9-11"/>
          </svg>
        </div>
        <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: 24, fontWeight: 400, margin: 0, letterSpacing: '-0.01em' }}>Thanks, Maria!</h2>
        <p style={{ color: '#5c5a54', fontSize: 14, margin: '8px 0 24px', maxWidth: 260, lineHeight: 1.5 }}>
          Your log for <b>{house.name}</b> on {fmtDate(form.date)} has been saved.
        </p>
        <div style={{ background: cardBg, borderRadius: 12, padding: 16, width: '100%', maxWidth: 280, textAlign: 'left', fontSize: 13, boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
            <span style={{ color: '#8a8780' }}>Cleaning fee</span>
            <span className="tabular" style={{ fontWeight: 500 }}>${house.cleaningRate}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
            <span style={{ color: '#8a8780' }}>Laundry</span>
            <span className="tabular" style={{ fontWeight: 500 }}>${form.laundryAmount || 0}</span>
          </div>
          <div style={{ borderTop: '1px solid #e8e6e0', marginTop: 6, paddingTop: 8, display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ fontWeight: 600 }}>Total billed</span>
            <span className="tabular" style={{ fontWeight: 600 }}>${house.cleaningRate + Number(form.laundryAmount || 0)}</span>
          </div>
        </div>
        <button onClick={reset} style={{
          marginTop: 28, height: 44, padding: '0 28px', borderRadius: 999,
          background: '#1a1a17', color: 'white', border: 0, fontSize: 14, fontWeight: 500, fontFamily: 'inherit',
        }}>Submit another</button>
      </div>
    );
  }

  // Group fields into cards — system fields (property/date) in first card, rest in separate cards
  const systemFields = fields.filter(f => f.system);
  const customFields = fields.filter(f => !f.system);

  return (
    <div style={{
      height: '100%', background: bg, overflow: 'auto', padding: '56px 20px 40px',
      fontFamily: 'Inter, system-ui', color: '#1a1a17', display: 'flex', flexDirection: 'column', gap: 16,
    }}>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
          <div style={{ width: 26, height: 26, borderRadius: 6, background: '#2d5f3f', color: 'white',
            display: 'grid', placeItems: 'center', fontFamily: 'Fraunces, serif', fontSize: 14, fontStyle: 'italic' }}>s</div>
          <span style={{ fontSize: 14, fontWeight: 500 }}>Slate</span>
        </div>
        <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 26, fontWeight: 400, margin: '8px 0 4px', letterSpacing: '-0.01em' }}>Log a cleaning</h1>
        <p style={{ fontSize: 13, color: '#5c5a54', margin: 0 }}>Hi Maria 👋 Fill this in after each turnover.</p>
      </div>

      {systemFields.length > 0 && (
        <div style={{ background: cardBg, borderRadius: 12, padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
          {systemFields.map(f => (
            <FormFieldRenderer key={f.id} field={f} value={form[f.id]} setValue={v => upd(f.id, v)} houses={store.houses}
                               hasReceipt={hasReceipt} setHasReceipt={setHasReceipt}/>
          ))}
        </div>
      )}

      {customFields.map((f, i) => (
        <div key={f.id} style={{ background: cardBg, borderRadius: 12, padding: 16 }}>
          <FormFieldRenderer field={f} value={form[f.id]} setValue={v => upd(f.id, v)} houses={store.houses}
                             hasReceipt={hasReceipt} setHasReceipt={setHasReceipt}/>
        </div>
      ))}

      <button onClick={submit} disabled={!isValid}
              style={{
                height: 50, borderRadius: 12, background: '#1a1a17', color: 'white', border: 0,
                fontSize: 15, fontWeight: 500, fontFamily: 'inherit', marginTop: 4,
                opacity: isValid ? 1 : 0.4,
              }}>Submit cleaning log</button>

      <div style={{ fontSize: 11.5, color: '#8a8780', textAlign: 'center', marginTop: 4 }}>
        {house && `Auto-bills $${house.cleaningRate} cleaning + $${Number(form.laundryAmount || 0)} laundry to ${house.name}.`}
      </div>
    </div>
  );
}

Object.assign(window, { CleanerMobileForm });
