/* =============================================================================
   portal/FeedbackSurvey.jsx — post-engagement client feedback survey.
   consultantNotes.meta.feedbackSurvey = { sentAt, message, submittedAt, answers }
   Thank-you screen only after submit (no locked answer view, per Karen).
   ============================================================================= */

const FS_SCHOOLS = ['Harvard Business School', 'Stanford GSB', 'Wharton', 'Columbia Business School', 'MIT Sloan', 'Chicago Booth', 'Kellogg', 'NYU', 'Duke', 'Darden', 'Tuck', 'Yale', 'INSEAD', 'London Business School', 'Cornell (Johnson)', 'Berkeley Haas', 'UCLA Anderson'];
const FS_OUTCOME_COLS = ['applied', 'interviewed', 'waitlisted', 'admitted', 'scholarship'];
const FS_OUTCOME_LABELS = { applied: 'Applied', interviewed: 'Interviewed', waitlisted: 'Waitlisted', admitted: 'Admitted', scholarship: 'Scholarship' };

function FeedbackSurvey({ onToast }) {
  const { C } = UI;
  const client = (window.CodataAPI && CodataAPI.getCurrentClient && CodataAPI.getCurrentClient()) || {};
  const [answers, setAnswers] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [loading, setLoading] = React.useState(true);
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr] = React.useState('');
  const set = (k, v) => setAnswers(a => ({ ...a, [k]: v }));

  // Hydrate from Codata (source of truth) on mount.
  React.useEffect(() => {
    if (!window.CodataAPI) { setLoading(false); return; }
    CodataAPI.getClientMeta().then(({ meta }) => {
      const fs = (meta && meta.feedbackSurvey) || {};
      if (fs.submittedAt) setSubmitted(true);
      if (fs.answers) setAnswers(fs.answers);
      if (window.KHSync && CodataAPI.getCurrentClientId) KHSync.patch(CodataAPI.getCurrentClientId(), { feedbackSurvey: fs });
    }).catch(e => console.error('Codata feedback-survey load failed:', e)).finally(() => setLoading(false));
  }, []);

  function submit() {
    setErr('');
    setSubmitting(true);
    const now = Date.now();
    const nextAnswers = answers;
    CodataAPI.getClientMeta().then(({ meta }) => {
      const fs = Object.assign({}, meta.feedbackSurvey, { answers: nextAnswers, submittedAt: now });
      return CodataAPI.saveClientMeta({ feedbackSurvey: fs }).then(() => fs);
    }).then(fs => {
      const cid = CodataAPI.getCurrentClientId && CodataAPI.getCurrentClientId();
      if (window.KHSync && cid) KHSync.patch(cid, { feedbackSurvey: fs });
      if (CodataAPI.logActivity) CodataAPI.logActivity('submit', 'Feedback Survey');
      if (CodataAPI.notifyAdminFeedbackSubmitted) {
        CodataAPI.notifyAdminFeedbackSubmitted(client.name || '', cid || '').catch(e => console.error('Feedback-survey email to Karen failed:', e));
      }
      setSubmitted(true);
      window.scrollTo(0, 0);
    }).catch(e => {
      setErr((e && e.code === 'NOTES_TOO_LARGE') ? e.message : "Couldn't submit your survey — please check your connection and try again.");
    }).finally(() => setSubmitting(false));
  }

  if (loading) return null;

  if (submitted) {
    return (
      <div className="kh-fade" style={{ maxWidth: 640, margin: '80px auto', padding: '4px 4px 60px', textAlign: 'center' }}>
        <div style={{ width: 52, height: 52, borderRadius: 999, background: 'var(--st-done-bg)', border: '1px solid var(--st-done-line)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 22px' }}>
          <Icon name="check" size={22} color="var(--st-done)" />
        </div>
        <h1 className="kh-display" style={{ fontSize: 'clamp(26px,3vw,36px)', margin: 0 }}>Thank you</h1>
        <p style={{ fontFamily: C.serif, fontSize: 15, lineHeight: 1.6, color: C.carbon70, marginTop: 14 }}>Your feedback means a great deal — thank you for taking the time to share it. It was a pleasure working with you.</p>
      </div>
    );
  }

  return (
    <div className="kh-fade" style={{ maxWidth: 760, margin: '0 auto', padding: '4px 4px 70px' }}>
      <div style={{ marginBottom: 30 }}>
        <h1 className="kh-display" style={{ fontSize: 'clamp(30px,3.6vw,44px)', margin: 0 }}>Feedback Survey</h1>
        <p style={{ fontFamily: C.serif, fontSize: 15, lineHeight: 1.6, color: C.carbon70, marginTop: 14, maxWidth: 620 }}>Thank you for sharing your feedback on our work together. It will be invaluable for helping me to learn and grow, to best support future clients.</p>
      </div>

      <FSSection title="General Experience">
        <FSField label="How would you rate your experience working together?" sub="5 = highest, 1 = lowest" required><FSRating value={answers.expRating} onChange={v => set('expRating', v)} /></FSField>
        <FSField label="Please describe your rating." required><FSText value={answers.expNote} onChange={v => set('expNote', v)} area /></FSField>
      </FSSection>

      <FSSection title="Communication">
        <FSField label="How did you feel about the level of communication, attention, and support during the application process?" sub="5 = highest, 1 = lowest"><FSRating value={answers.commRating} onChange={v => set('commRating', v)} /></FSField>
        <FSField label="Please describe your rating."><FSText value={answers.commNote} onChange={v => set('commNote', v)} area /></FSField>
      </FSSection>

      <FSSection title="Services">
        <FSField label="Which aspect(s) of our work did you find most helpful?"><FSText value={answers.helpfulAspects} onChange={v => set('helpfulAspects', v)} area /></FSField>
        <FSField label="Which resources and materials did you find most beneficial?"><FSText value={answers.beneficialResources} onChange={v => set('beneficialResources', v)} area /></FSField>
        <FSField label="Were there any additional services, resources, or materials you felt would have been beneficial?"><FSText value={answers.additionalServices} onChange={v => set('additionalServices', v)} area /></FSField>
      </FSSection>

      <FSSection title="Outcome">
        <FSField label="How satisfied are you with the outcome?" sub="5 = highest, 1 = lowest"><FSRating value={answers.outcomeRating} onChange={v => set('outcomeRating', v)} /></FSField>
        <FSField label="Please describe your rating."><FSText value={answers.outcomeNote} onChange={v => set('outcomeNote', v)} area /></FSField>
        <FSField label="Please share outcomes for all schools you applied to"><FSOutcomesTable value={answers.outcomes} onChange={v => set('outcomes', v)} /></FSField>
        <FSField label="Please list all scholarships awarded"><FSText value={answers.scholarships} onChange={v => set('scholarships', v)} area rows={3} /></FSField>
        <FSField label="Which school will you be attending?"><FSSchoolSelect value={answers.attendingSchool} otherValue={answers.attendingSchoolOther} onChange={v => set('attendingSchool', v)} onOtherChange={v => set('attendingSchoolOther', v)} /></FSField>
      </FSSection>

      <FSSection title="Challenges">
        <FSField label="What challenges did you face during the application process, and how could I have better helped you address them?"><FSText value={answers.challenges} onChange={v => set('challenges', v)} area /></FSField>
      </FSSection>

      <FSSection title="Suggestions">
        <FSField label="Is there anything you suggest I improve when working with future clients?"><FSText value={answers.improveSuggestion} onChange={v => set('improveSuggestion', v)} area /></FSField>
        <FSField label="Do you have any ideas or suggestions for improving the client platform?"><FSText value={answers.platformSuggestion} onChange={v => set('platformSuggestion', v)} area /></FSField>
        <FSField label="What initially led you to choose to work with me? Were there any hesitations during your decision-making process? In retrospect, is there anything you wish had been included or communicated upfront, especially compared to what other consultants may have offered?"><FSText value={answers.decisionProcess} onChange={v => set('decisionProcess', v)} area /></FSField>
        <FSField label="How many hours per week, on average, do you think you dedicated to our process? Did this time commitment align with your initial expectations?"><FSText value={answers.hoursPerWeek} onChange={v => set('hoursPerWeek', v)} area rows={3} /></FSField>
      </FSSection>

      <FSSection title="Next Steps">
        <FSField label="How likely are you to recommend me to others?" sub="5 = highest, 1 = lowest"><FSRating value={answers.recommendRating} onChange={v => set('recommendRating', v)} /></FSField>
        <FSField label="Please describe your rating."><FSText value={answers.recommendNote} onChange={v => set('recommendNote', v)} area /></FSField>
        <FSField label="Would you be willing to write a brief testimonial for my profile on the Poets &amp; Quants site?" required>
          <a href="https://poetsandquants.com/consultant/karen-hamou-2/" target="_blank" rel="noreferrer" style={{ display: 'inline-block', fontFamily: C.sans, fontSize: 13, color: C.carbon, marginBottom: 10 }}>poetsandquants.com/consultant/karen-hamou-2</a>
          <FSRadio value={answers.testimonial} onChange={v => set('testimonial', v)} options={['Yes', 'No', 'Already did!']} />
        </FSField>
        <FSField label="Do you give permission for a cleansed version of your resume with no identifying information to be used as a sample for future clients?"><FSRadio value={answers.resumePermission} onChange={v => set('resumePermission', v)} options={['Yes', 'No']} /></FSField>
        <FSField label="Would you like to connect with other clients of mine who will be attending the school you are attending? I often make email introductions over the summer before school starts."><FSRadio value={answers.connectClients} onChange={v => set('connectClients', v)} options={['Yes', 'No']} /></FSField>
        <FSField label="Would you be willing to speak with my future clients who may be interested in the school you are attending?"><FSRadio value={answers.speakFuture} onChange={v => set('speakFuture', v)} options={['Yes', 'No']} /></FSField>
      </FSSection>

      <FSSection title="Additional Comments">
        <FSField label="Is there anything else you would like to share?"><FSText value={answers.additionalComments} onChange={v => set('additionalComments', v)} area /></FSField>
      </FSSection>

      {err && <div style={{ fontFamily: C.sans, fontSize: 12.5, color: 'var(--sch-overdue, #B4483A)', marginBottom: 14 }}>{err}</div>}

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 8 }}>
        <button onClick={submit} disabled={submitting} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: C.sans, fontWeight: 600, fontSize: 11.5, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '13px 22px', border: 'none', cursor: submitting ? 'default' : 'pointer', background: C.carbon, color: '#fff', opacity: submitting ? 0.6 : 1 }}>
          <Icon name="check" size={15} color="#fff" /> {submitting ? 'Submitting…' : 'Submit survey'}
        </button>
      </div>
    </div>
  );
}

function FSSection({ title, note, children }) {
  const { C } = UI;
  return (
    <div style={{ marginBottom: 30, paddingBottom: 30, borderBottom: `1px solid ${C.hair}` }}>
      <div className="kh-eyebrow" style={{ marginBottom: note ? 6 : 16 }}>{title}</div>
      {note && <p style={{ fontFamily: C.serif, fontStyle: 'italic', fontSize: 13.5, lineHeight: 1.5, color: C.carbon50, margin: '0 0 16px' }}>{note}</p>}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>{children}</div>
    </div>
  );
}
function FSField({ label, sub, required, children }) {
  const { C } = UI;
  return (
    <div>
      <label style={{ display: 'block', fontFamily: C.sans, fontWeight: 600, fontSize: 13.5, lineHeight: 1.5, color: C.carbon, marginBottom: sub ? 3 : 9 }}>
        {label}{required && <span style={{ color: 'var(--sch-denied-pre)', marginLeft: 4 }}>*</span>}
      </label>
      {sub && <div style={{ fontFamily: C.sans, fontSize: 11.5, color: C.carbon50, marginBottom: 9 }}>{sub}</div>}
      {children}
    </div>
  );
}
function FSText({ value, onChange, area, rows, type }) {
  const { C } = UI;
  const base = { width: '100%', fontFamily: area ? C.serif : C.sans, fontSize: area ? 15 : 14, lineHeight: area ? 1.6 : 1.4, color: C.carbon, background: '#fff', border: `1px solid var(--border-rule)`, borderRadius: 2, padding: '11px 13px', outline: 'none', boxSizing: 'border-box' };
  return area
    ? <textarea value={value || ''} onChange={e => onChange(e.target.value)} rows={rows || 5} style={{ ...base, resize: 'vertical' }} />
    : <input type={type || 'text'} value={value || ''} onChange={e => onChange(e.target.value)} style={base} />;
}
function FSRating({ value, onChange }) {
  const { C } = UI;
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      {[1, 2, 3, 4, 5].map(n => {
        const on = value === n;
        return (
          <button key={n} onClick={() => onChange(n)} style={{ width: 42, height: 42, borderRadius: 999, border: `1.5px solid ${on ? C.carbon : C.carbon30}`, background: on ? C.carbon : 'transparent', color: on ? '#fff' : C.carbon, cursor: 'pointer', fontFamily: C.sans, fontSize: 15, fontWeight: 600 }}>{n}</button>
        );
      })}
    </div>
  );
}
function FSRadio({ value, onChange, options }) {
  const { C } = UI;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {options.map(opt => {
        const on = value === opt;
        return (
          <button key={opt} onClick={() => onChange(opt)} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: C.sans, fontSize: 14, color: C.carbon, textAlign: 'left', alignSelf: 'flex-start' }}>
            <span style={{ width: 18, height: 18, flexShrink: 0, borderRadius: 999, border: `1.5px solid ${on ? C.carbon : C.carbon30}`, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{on && <span style={{ width: 9, height: 9, borderRadius: 999, background: C.carbon }} />}</span>
            {opt}
          </button>
        );
      })}
    </div>
  );
}
function FSSchoolSelect({ value, otherValue, onChange, onOtherChange }) {
  const { C } = UI;
  const isOther = value === 'Other';
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 340 }}>
      <select value={value || ''} onChange={e => onChange(e.target.value)} style={{ fontFamily: C.sans, fontSize: 14, color: C.carbon, background: '#fff', border: `1px solid var(--border-rule)`, borderRadius: 2, padding: '11px 13px', outline: 'none', cursor: 'pointer' }}>
        <option value="">Select a school…</option>
        {FS_SCHOOLS.map(s => <option key={s} value={s}>{s}</option>)}
        <option value="Other">Other</option>
      </select>
      {isOther && <FSText value={otherValue} onChange={onOtherChange} />}
    </div>
  );
}
function FSOutcomesTable({ value, onChange }) {
  const { C } = UI;
  const v = value || {};
  const toggle = (school, col) => {
    const row = v[school] || {};
    onChange({ ...v, [school]: { ...row, [col]: !row[col] } });
  };
  return (
    <div style={{ overflowX: 'auto', border: `1px solid ${C.hair}` }}>
      <table style={{ borderCollapse: 'collapse', width: '100%', minWidth: 560 }}>
        <thead>
          <tr>
            <th style={fsTh(C, 'left')}>School</th>
            {FS_OUTCOME_COLS.map(c => <th key={c} style={fsTh(C)}>{FS_OUTCOME_LABELS[c]}</th>)}
          </tr>
        </thead>
        <tbody>
          {FS_SCHOOLS.map((s, i) => (
            <tr key={s} style={{ background: i % 2 ? C.porcelain : '#fff' }}>
              <td style={{ ...fsTd(C), textAlign: 'left', fontWeight: 500 }}>{s}</td>
              {FS_OUTCOME_COLS.map(c => (
                <td key={c} style={fsTd(C)}>
                  <button onClick={() => toggle(s, c)} style={{ width: 18, height: 18, border: `1.5px solid ${(v[s] || {})[c] ? C.carbon : C.carbon30}`, borderRadius: 3, background: (v[s] || {})[c] ? C.carbon : 'transparent', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                    {(v[s] || {})[c] && <Icon name="check" size={12} color="#fff" />}
                  </button>
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
function fsTh(C, align) { return { fontFamily: C.sans, fontSize: 10, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: C.carbon70, padding: '10px 12px', textAlign: align || 'center', borderBottom: `1px solid ${C.hair}`, whiteSpace: 'nowrap' }; }
function fsTd(C) { return { padding: '9px 12px', textAlign: 'center', fontFamily: C.sans, fontSize: 13, color: C.carbon }; }

window.FeedbackSurvey = FeedbackSurvey;
window.FS_OUTCOME_COLS = FS_OUTCOME_COLS;
window.FS_OUTCOME_LABELS = FS_OUTCOME_LABELS;
