/* Viamar — Stage 2 details + Stage 3 specialist review for a saved live case. */

function CaseFlowField({ id, label, value, onChange, error, placeholder }) {
  return (
    <label htmlFor={id} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontFamily: FM, fontSize: 10, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: T.faint }}>{label}</span>
      <input
        id={id}
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        aria-invalid={!!error}
        aria-describedby={error ? id + '-error' : undefined}
        style={{ width: '100%', border: '1.5px solid ' + (error ? T.red : T.line), borderRadius: 12, padding: '12px 13px', background: '#fff', color: T.ink, fontFamily: FB, fontSize: 14, outline: 'none' }}
      />
      {error && <span id={id + '-error'} style={{ color: T.red, fontFamily: FB, fontSize: 11.5 }}>{error}</span>}
    </label>
  );
}

function caseStatusLabel(value) {
  return {
    request_saved: 'Request saved',
    under_review: 'Under review',
    waiting_customer: 'Waiting for you',
    quote_ready: 'Quote ready',
    closed: 'Closed',
  }[value] || 'Under review';
}

function caseDeadline(value) {
  if (!value) return 'Within one business day';
  const date = new Date(value);
  if (isNaN(date.getTime())) return 'Within one business day';
  return date.toLocaleString('en-CA', {
    weekday: 'short',
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  });
}

function caseHeadline(status) {
  if (status === 'quote_ready') return 'Your quote is ready';
  if (status === 'closed') return 'This request is closed';
  if (status === 'waiting_customer') return 'We need one more detail from you';
  return 'A Viamar specialist is reviewing your shipment.';
}

function caseStatusDetail(status) {
  if (status === 'quote_ready') return 'Your specialist has released the price and conditions below.';
  if (status === 'closed') return 'Contact Viamar if you would like to reopen or replace this request.';
  if (status === 'waiting_customer') return 'Review the next action below so your specialist can continue.';
  return 'We will ask only for anything still needed and keep this request updated here.';
}

function actionOwnerLabel(value) {
  if (value === 'customer') return 'You';
  if (value === 'none') return 'No action needed';
  return 'Viamar';
}

function casePrice(value, currency) {
  if (value == null || value === '') return null;
  const price = Number(value);
  if (!Number.isFinite(price)) return null;
  return new Intl.NumberFormat('en-CA', {
    style: 'currency',
    currency: currency || 'CAD',
    maximumFractionDigits: 2,
  }).format(price);
}

function CaseFlow({ intakeResult, onClose, onComplete }) {
  const workflow = window.ViamarCaseWorkflow;
  const initial = React.useMemo(
    () => workflow.initialDetails(intakeResult || {}),
    [intakeResult]
  );
  const [details, setDetails] = React.useState(initial);
  const [fields, setFields] = React.useState({});
  const [files, setFiles] = React.useState([]);
  const [stage, setStage] = React.useState(
    intakeResult
      && intakeResult.case
      && ['request_saved', 'waiting_customer'].includes(intakeResult.case.customer_status)
      ? 'details'
      : 'review'
  );
  const [caseView, setCaseView] = React.useState((intakeResult && intakeResult.case) || {});
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const [uploadNote, setUploadNote] = React.useState('');

  const set = patch => {
    setDetails(current => ({ ...current, ...patch }));
    setFields({});
    setError('');
  };

  const submit = async e => {
    e.preventDefault();
    const checked = workflow.validateDetails(details);
    if (!checked.valid) {
      setFields(checked.fields);
      return;
    }
    if (!window.ViamarAPI || !ViamarAPI.updateCaseDetails) {
      setError('The request service is unavailable. Please call 1-800-277-7570.');
      return;
    }

    setSubmitting(true);
    setError('');
    const documentRefs = [];
    if (files.length && ViamarAPI.uploadDocument) {
      for (const file of files) {
        try {
          const uploaded = await ViamarAPI.uploadDocument({
            file,
            quote_ref: initial.case_id,
            document_type: 'customer_supporting_document',
            cargo_type: details.category,
            source: 'live-case-details',
          });
          if (uploaded && uploaded.upload_id) documentRefs.push(uploaded.upload_id);
        } catch (uploadError) {
          setUploadNote('Your details were saved, but one optional document needs to be added again.');
        }
      }
    }

    try {
      const sessionToken = intakeResult.session_token
        || (ViamarAPI.session() && ViamarAPI.session().session_token);
      const payload = workflow.toDetailsPayload(
        { ...details, document_refs: documentRefs },
        sessionToken
      );
      const updated = await ViamarAPI.updateCaseDetails(initial.case_id, payload);
      let projected = updated.case || {};
      if (ViamarAPI.customerState) {
        try {
          const state = await ViamarAPI.customerState();
          const found = (state.quotes || []).find(q => q.id === initial.case_id);
          if (found) projected = found;
        } catch (refreshError) {}
      }
      setCaseView(projected);
      setStage('review');
      if (window.ViamarStore && ViamarStore.syncCustomerState) {
        ViamarStore.syncCustomerState().catch(() => {});
      }
      if (window.ViamarAnalytics) {
        ViamarAnalytics.track('case_details_submitted', {
          case_id: initial.case_id,
          assessment_mode: details.assessment_mode,
          document_count: documentRefs.length,
        });
      }
      if (onComplete) onComplete(projected);
    } catch (submitError) {
      setError((submitError && submitError.message) || 'We could not save these details.');
    } finally {
      setSubmitting(false);
    }
  };

  const recovery = (intakeResult && intakeResult.recovery) || {};
  const recoverySent = ['webhook_sent', 'ghl_sent'].includes(recovery.delivery);
  const status = caseView.customer_status || (stage === 'review' ? 'under_review' : 'request_saved');
  const releasedPrice = status === 'quote_ready'
    ? casePrice(caseView.final_price, caseView.currency)
    : null;

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="case-flow-title" style={{ position: 'fixed', inset: 0, zIndex: 120, background: 'rgba(6,20,34,.78)', backdropFilter: 'blur(6px)', overflowY: 'auto', padding: 'max(18px, env(safe-area-inset-top)) 16px max(24px, env(safe-area-inset-bottom))' }}>
      <div style={{ width: '100%', maxWidth: 760, margin: '0 auto', background: T.paper, borderRadius: 24, overflow: 'hidden', boxShadow: '0 28px 80px rgba(0,0,0,.34)' }}>
        <header style={{ background: T.navy, color: '#fff', padding: '22px 24px', display: 'flex', alignItems: 'flex-start', gap: 16 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: FM, fontSize: 10, color: 'rgba(255,255,255,.58)', letterSpacing: '.12em', textTransform: 'uppercase' }}>
              {stage === 'details' ? 'Details · Step 2 of 3' : 'Specialist review · Step 3 of 3'} · {initial.case_id}
            </div>
            <div id="case-flow-title" style={{ fontFamily: FD, fontWeight: 900, fontSize: 25, lineHeight: 1.15, marginTop: 7 }}>
              {stage === 'details' ? 'Add the shipment details' : 'Your specialist has the request'}
            </div>
          </div>
          <button type="button" onClick={onClose} aria-label="Close case flow" style={{ width: 38, height: 38, borderRadius: 11, border: '1px solid rgba(255,255,255,.18)', background: 'rgba(255,255,255,.08)', color: '#fff', fontSize: 22, cursor: 'pointer' }}>×</button>
        </header>

        {stage === 'details' ? (
          <form onSubmit={submit} style={{ padding: 24 }}>
            <div role="status" style={{ background: '#fff', border: '1px solid rgba(46,139,111,.28)', borderRadius: 14, padding: '13px 15px', color: T.body, fontFamily: FB, fontSize: 13, lineHeight: 1.5 }}>
              <strong style={{ color: T.ink }}>Request saved.</strong> Add the route and a written list. Photos and documents are optional.
            </div>

            <section aria-labelledby="case-route-heading" style={{ marginTop: 24 }}>
              <div id="case-route-heading" style={{ fontFamily: FD, fontWeight: 800, fontSize: 18, color: T.ink }}>Route</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 12, marginTop: 12 }}>
                <CaseFlowField id="case-origin" label="From" value={details.origin} onChange={origin => set({ origin })} error={fields.origin} placeholder="Toronto, Canada" />
                <CaseFlowField id="case-destination" label="To" value={details.destination} onChange={destination => set({ destination })} error={fields.destination} placeholder="Lisbon, Portugal" />
              </div>
            </section>

            <section aria-labelledby="case-inventory-heading" style={{ marginTop: 24 }}>
              <div id="case-inventory-heading" style={{ fontFamily: FD, fontWeight: 800, fontSize: 18, color: T.ink }}>What is moving?</div>
              <label htmlFor="case-inventory" style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 12 }}>
                <span style={{ fontFamily: FB, fontSize: 12.5, color: T.body }}>A simple written list is enough.</span>
                <textarea id="case-inventory" rows="5" value={details.inventory_text} onChange={e => set({ inventory_text: e.target.value })} aria-invalid={!!fields.inventory_text} aria-describedby={fields.inventory_text ? 'case-inventory-error' : undefined} placeholder="Example: sofa, dining table, 12 boxes and 2 bicycles" style={{ resize: 'vertical', width: '100%', border: '1.5px solid ' + (fields.inventory_text ? T.red : T.line), borderRadius: 12, padding: 13, background: '#fff', color: T.ink, fontFamily: FB, fontSize: 14, lineHeight: 1.5, outline: 'none' }} />
                {fields.inventory_text && <span id="case-inventory-error" style={{ color: T.red, fontFamily: FB, fontSize: 11.5 }}>{fields.inventory_text}</span>}
              </label>
            </section>

            <fieldset style={{ border: 0, padding: 0, margin: '24px 0 0' }}>
              <legend style={{ fontFamily: FD, fontWeight: 800, fontSize: 18, color: T.ink }}>Assessment</legend>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 10, marginTop: 12 }}>
                {[
                  ['specialist', 'Specialist assessment', 'Recommended · no photos needed'],
                  ['ai_photo', 'AI / photo assessment', 'Optional · add photos if useful'],
                ].map(([id, title, sub]) => {
                  const selected = details.assessment_mode === id;
                  return (
                    <button key={id} type="button" aria-pressed={selected} onClick={() => set({ assessment_mode: id })} style={{ textAlign: 'left', border: '1.5px solid ' + (selected ? T.red : T.line), background: selected ? 'rgba(221,28,36,.06)' : '#fff', borderRadius: 13, padding: 14, cursor: 'pointer' }}>
                      <span style={{ display: 'block', color: T.ink, fontFamily: FB, fontWeight: 800, fontSize: 13.5 }}>{title}</span>
                      <span style={{ display: 'block', color: T.muted, fontFamily: FB, fontSize: 11.5, marginTop: 3 }}>{sub}</span>
                    </button>
                  );
                })}
              </div>
            </fieldset>

            <section aria-labelledby="case-docs-heading" style={{ marginTop: 24, borderTop: '1px solid ' + T.line2, paddingTop: 20 }}>
              <div id="case-docs-heading" style={{ fontFamily: FD, fontWeight: 800, fontSize: 18, color: T.ink }}>Optional documents</div>
              <div style={{ fontFamily: FB, fontSize: 12.5, color: T.muted, lineHeight: 1.5, marginTop: 5 }}>Add an item list, vehicle registration, or specification sheet now—or later.</div>
              <input type="file" multiple onChange={e => setFiles(Array.from(e.target.files || []).slice(0, 6))} style={{ marginTop: 12, fontFamily: FB, fontSize: 12, maxWidth: '100%' }} />
              {!!files.length && <div style={{ fontFamily: FM, fontSize: 10, color: T.faint, marginTop: 7 }}>{files.length} optional file{files.length === 1 ? '' : 's'} selected</div>}
            </section>

            {error && <div role="alert" style={{ marginTop: 16, padding: '11px 13px', borderRadius: 11, background: 'rgba(221,28,36,.08)', color: T.red, fontFamily: FB, fontSize: 12.5 }}>{error}</div>}
            <button type="submit" disabled={submitting} style={{ width: '100%', border: 0, borderRadius: 13, padding: '14px 18px', background: submitting ? T.line : T.red, color: '#fff', fontFamily: FB, fontWeight: 800, fontSize: 14, cursor: submitting ? 'wait' : 'pointer', marginTop: 20 }}>
              {submitting ? 'Saving details…' : 'Send to my specialist'}
            </button>
          </form>
        ) : (
          <div style={{ padding: 24 }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, background: '#fff', border: '1px solid ' + T.line2, borderRadius: 18, padding: 18 }}>
              <div style={{ width: 44, height: 44, borderRadius: 14, background: T.green, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="check" size={23} color="#fff" stroke={3} /></div>
              <div>
                <Kicker color={T.green} style={{ marginBottom: 5 }}>{caseStatusLabel(status)}</Kicker>
                <Display size={22} color={T.ink}>{caseHeadline(status)}</Display>
                <div style={{ fontFamily: FB, fontSize: 13, lineHeight: 1.5, color: T.body, marginTop: 7 }}>{caseStatusDetail(status)}</div>
              </div>
            </div>

            <dl style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(210px,1fr))', gap: 12, margin: '18px 0 0' }}>
              {[
                ['Reference', initial.case_id],
                ['Specialist', caseView.specialist_name || 'Viamar specialist'],
                ['Response by', caseDeadline(caseView.response_due_at)],
                ['Next action', caseView.next_action || 'Viamar is reviewing your shipment details.'],
                ['Action owner', actionOwnerLabel(caseView.next_action_owner)],
                ...(releasedPrice ? [['Released price', releasedPrice]] : []),
                ...(status === 'quote_ready' && caseView.quoted_conditions
                  ? [['Quote conditions', caseView.quoted_conditions]]
                  : []),
                ['Return access', recoverySent ? 'Secure return link sent' : 'Use your reference or contact Viamar'],
              ].map(([label, value]) => (
                <div key={label} style={{ background: '#fff', border: '1px solid ' + T.line2, borderRadius: 13, padding: 14 }}>
                  <dt style={{ fontFamily: FM, fontSize: 9.5, color: T.faint, letterSpacing: '.08em', textTransform: 'uppercase' }}>{label}</dt>
                  <dd style={{ margin: '6px 0 0', fontFamily: FB, fontWeight: 700, fontSize: 13, lineHeight: 1.4, color: T.ink }}>{value}</dd>
                </div>
              ))}
            </dl>
            {uploadNote && <div role="status" style={{ marginTop: 14, color: T.amber, fontFamily: FB, fontSize: 12.5 }}>{uploadNote}</div>}
            <button type="button" onClick={onClose} style={{ width: '100%', border: 0, borderRadius: 13, padding: '14px 18px', background: T.navy, color: '#fff', fontFamily: FB, fontWeight: 800, fontSize: 14, cursor: 'pointer', marginTop: 20 }}>Return to dashboard</button>
          </div>
        )}
      </div>
    </div>
  );
}

window.ViamarLiveCase = { CaseFlow };
