import React, { useState } from 'react';
import { CheckCircle2, ChevronRight, RotateCcw, Compass } from 'lucide-react';

const CareAssessment = () => {
  const [currentScreen, setCurrentScreen] = useState('intro');
  const [scenario, setScenario] = useState('');
  
  const questions = [
    ["I'm good at recognizing alternatives.", "I tend to focus on many things at once.", "I like to see the consequences before I act.", "I like to examine the details."],
    ["I prefer to be actively involved in things.", "I enjoy getting attention.", "I like to use ideas others have thought through.", "I like to take things one step at a time."],
    ["I like to discuss concepts.", "I don't feel obligated to follow tradition.", "I prefer to test new things on a small scale before implementing a change.", "I like things to be balanced and symmetrical."],
    ["I'm good at exploring alternatives.", "I let my feelings guide me.", "I am uncomfortable when things are changing.", "Others might say I think like 1-2-3-4-5."],
    ["I like to focus on coming up with new ideas.", "I tend to move from one subject to another.", "I let accepted norms and expectations guide me.", "I prefer to think things over carefully before acting."],
    ["I like to develop theories and principles.", "When everything is in place, I am restless.", "I tend to be cautious in trying out a new approach.", "I like to be in a place where there is order."],
    ["I'm good at visualizing the master plan.", "Others might say I think like 1-3-2-purple-5-alligator.", "I don't challenge the status quo.", "My ideas focus on what I can prove is true."],
    ["I often think about what should happen next.", "I sometimes get impatient.", "I try to fit in with other people.", "I tend to follow a process when solving problems."],
    ["I'm good at capturing the essential core of a matter.", "I let my own preferences guide me.", "I prefer to let others take the lead.", "I am comfortable being methodical."],
    ["I'm good at analyzing things.", "I like to have respect.", "I like to see things fit together.", "I'm good at putting things in order."],
    ["I like to discuss implementation.", "I sometimes act impulsively.", "Initially, I respond to new ideas with skepticism.", "I prefer to spend my time creating order."],
    ["I prefer to focus on the future.", "I like to have influence.", "I prefer to try a proven solution, rather than try something unproven.", "A good description of my thought process would be step-by-step."]
  ];

  const [rankings, setRankings] = useState(
    Array(12).fill(null).map(() => [null, null, null, null])
  );

  const handleRankChange = (rowIndex, colIndex, value) => {
    const newRankings = [...rankings];
    const numValue = value === '' ? null : parseInt(value);
    
    const currentRow = newRankings[rowIndex];
    if (numValue !== null) {
      const existingIndex = currentRow.indexOf(numValue);
      if (existingIndex !== -1 && existingIndex !== colIndex) {
        currentRow[existingIndex] = null;
      }
    }
    
    newRankings[rowIndex][colIndex] = numValue;
    setRankings(newRankings);
  };

  const getRowTotal = (rowIndex) => {
    return rankings[rowIndex].reduce((sum, val) => sum + (val || 0), 0);
  };

  const isRowComplete = (rowIndex) => {
    const row = rankings[rowIndex];
    return row.every(val => val !== null) && getRowTotal(rowIndex) === 10;
  };

  const allRowsComplete = () => {
    return rankings.every((_, idx) => isRowComplete(idx));
  };

  const getTotalScore = () => {
    return rankings.reduce((total, row) => 
      total + row.reduce((sum, val) => sum + (val || 0), 0), 0
    );
  };

  const calculateResults = () => {
    const totals = [0, 0, 0, 0];
    rankings.forEach(row => {
      row.forEach((val, idx) => {
        totals[idx] += val || 0;
      });
    });
    return totals;
  };

  const getPrimaryTypes = () => {
    const totals = calculateResults();
    const max = Math.max(...totals);
    const types = ['X', 'T', 'C', 'S'];
    const primaryTypes = [];
    totals.forEach((total, idx) => {
      if (total === max) {
        primaryTypes.push(types[idx]);
      }
    });
    return primaryTypes;
  };

  if (currentScreen === 'intro') {
    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 p-4 font-sans">
        <style>{`
          @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
          * { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
        `}</style>
        <div className="max-w-2xl mx-auto pt-12 pb-8">
          <div className="bg-white rounded-3xl shadow-2xl overflow-hidden backdrop-blur-xl bg-opacity-95">
            <div className="p-8 md:p-12">
              <div className="text-center mb-8">
                <div className="w-20 h-20 bg-gradient-to-br from-purple-500 to-violet-600 rounded-3xl mx-auto mb-6 flex items-center justify-center shadow-lg transform rotate-3">
                  <Compass className="text-white transform -rotate-3" size={40} strokeWidth={2.5} />
                </div>
                <h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-3 tracking-tight">
                  C.A.R.E. Profile
                </h1>
                <p className="text-lg text-gray-500 font-medium">
                  Discover your Team Dimension
                </p>
              </div>

              <div className="grid grid-cols-2 gap-3 mb-6">
                {[
                  { letter: 'C', label: 'Creator', color: 'bg-orange-100 text-orange-700 border-orange-200', desc: 'Big-picture thinkers who generate new ideas' },
                  { letter: 'A', label: 'Advancer', color: 'bg-pink-100 text-pink-700 border-pink-200', desc: 'Energetic champions who move ideas forward' },
                  { letter: 'R', label: 'Refiner', color: 'bg-green-100 text-green-700 border-green-200', desc: 'Systematic thinkers who perfect the details' },
                  { letter: 'E', label: 'Executor', color: 'bg-blue-100 text-blue-700 border-blue-200', desc: 'Dependable implementers who get things done' },
                ].map(({ letter, label, color, desc }) => (
                  <div key={letter} className={`rounded-2xl p-4 border ${color}`}>
                    <div className="text-2xl font-bold mb-1">{letter}</div>
                    <div className="font-semibold text-sm mb-1">{label}</div>
                    <div className="text-xs opacity-80">{desc}</div>
                  </div>
                ))}
              </div>

              <div className="bg-gradient-to-br from-purple-50 to-violet-50 rounded-2xl p-6 mb-8 border border-purple-100">
                <h2 className="font-semibold text-gray-900 mb-4 text-lg">How it works:</h2>
                <div className="space-y-3">
                  <div className="flex gap-3">
                    <div className="w-7 h-7 bg-purple-500 rounded-full flex items-center justify-center flex-shrink-0 text-white text-sm font-semibold">1</div>
                    <p className="text-gray-700 leading-relaxed">Choose your context — a specific team, project, or organization you have in mind.</p>
                  </div>
                  <div className="flex gap-3">
                    <div className="w-7 h-7 bg-purple-500 rounded-full flex items-center justify-center flex-shrink-0 text-white text-sm font-semibold">2</div>
                    <p className="text-gray-700 leading-relaxed">For each question, rank all 4 statements — <strong>4</strong> for the one most like you, <strong>1</strong> for least like you. Use each number only once per row.</p>
                  </div>
                  <div className="flex gap-3">
                    <div className="w-7 h-7 bg-purple-500 rounded-full flex items-center justify-center flex-shrink-0 text-white text-sm font-semibold">3</div>
                    <p className="text-gray-700 leading-relaxed">Each row must total 10. Your complete assessment will total 120.</p>
                  </div>
                </div>
              </div>

              <div className="mb-8">
                <label className="block text-gray-900 font-semibold mb-3 text-sm tracking-wide uppercase">
                  Context (Optional)
                </label>
                <input
                  type="text"
                  placeholder="e.g., My work team"
                  value={scenario}
                  onChange={(e) => setScenario(e.target.value)}
                  className="w-full px-5 py-4 bg-gray-50 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all text-gray-900 placeholder-gray-400"
                />
              </div>

              <button
                onClick={() => setCurrentScreen('assessment')}
                className="w-full bg-gradient-to-r from-purple-500 to-violet-600 text-white py-5 rounded-xl font-semibold text-lg hover:from-purple-600 hover:to-violet-700 transition-all shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98] flex items-center justify-center gap-2"
              >
                Get Started
                <ChevronRight size={20} strokeWidth={2.5} />
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (currentScreen === 'assessment') {
    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 p-4 pb-32 font-sans">
        <style>{`
          @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
          * { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
          input[type="number"]::-webkit-inner-spin-button,
          input[type="number"]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
          }
          input[type="number"] {
            -moz-appearance: textfield;
          }
        `}</style>
        <div className="max-w-3xl mx-auto pt-6">
          <div className="bg-white rounded-3xl shadow-xl p-6 mb-6 backdrop-blur-xl bg-opacity-95">
            <h1 className="text-3xl font-bold text-gray-900 mb-2 tracking-tight">
              Assessment
            </h1>
            {scenario && (
              <p className="text-gray-600">
                <span className="font-medium text-gray-900">{scenario}</span>
              </p>
            )}
          </div>

          {questions.map((row, rowIndex) => (
            <div key={rowIndex} className="bg-white rounded-3xl shadow-xl p-6 mb-5 backdrop-blur-xl bg-opacity-95">
              <div className="flex items-center justify-between mb-5">
                <span className="text-sm font-semibold text-gray-500 tracking-wide uppercase">
                  Question {rowIndex + 1} of 12
                </span>
                <div className="flex items-center gap-2">
                  {isRowComplete(rowIndex) ? (
                    <span className="flex items-center gap-1.5 text-green-600 font-medium text-sm bg-green-50 px-3 py-1.5 rounded-full">
                      <CheckCircle2 size={16} strokeWidth={2.5} />
                      Complete
                    </span>
                  ) : (
                    <span className="text-gray-400 font-medium text-sm bg-gray-100 px-3 py-1.5 rounded-full">
                      {getRowTotal(rowIndex)}/10
                    </span>
                  )}
                </div>
              </div>

              <div className="space-y-3">
                {row.map((characteristic, colIndex) => (
                  <div key={colIndex} className="flex items-center gap-4 bg-gradient-to-r from-gray-50 to-transparent rounded-2xl p-3 hover:from-purple-50 transition-all">
                    <select
                      value={rankings[rowIndex][colIndex] || ''}
                      onChange={(e) => handleRankChange(rowIndex, colIndex, e.target.value)}
                      className="w-14 h-14 text-center text-2xl font-bold bg-white border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all shadow-sm cursor-pointer flex-shrink-0"
                    >
                      <option value="">—</option>
                      <option value="1">1</option>
                      <option value="2">2</option>
                      <option value="3">3</option>
                      <option value="4">4</option>
                    </select>
                    <label className="flex-1 text-gray-800 font-medium leading-snug">
                      {characteristic}
                    </label>
                  </div>
                ))}
              </div>

              {getRowTotal(rowIndex) > 0 && getRowTotal(rowIndex) !== 10 && (
                <div className="mt-4 bg-amber-50 border-2 border-amber-200 rounded-xl p-3 text-amber-800 text-sm font-medium">
                  Row must total 10 (currently {getRowTotal(rowIndex)})
                </div>
              )}
            </div>
          ))}

          <div className="fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-xl border-t border-gray-200 p-4 shadow-2xl">
            <div className="max-w-3xl mx-auto">
              <div className="mb-4">
                <div className="flex justify-between text-sm mb-2 font-medium">
                  <span className="text-gray-600">Progress</span>
                  <span className="text-gray-900">
                    {rankings.filter((_, idx) => isRowComplete(idx)).length} of 12 complete
                  </span>
                </div>
                <div className="h-3 bg-gray-200 rounded-full overflow-hidden shadow-inner">
                  <div 
                    className="h-full bg-gradient-to-r from-purple-500 to-violet-600 transition-all duration-500 ease-out rounded-full"
                    style={{ width: `${(rankings.filter((_, idx) => isRowComplete(idx)).length / 12) * 100}%` }}
                  />
                </div>
              </div>

              <button
                onClick={() => setCurrentScreen('results')}
                disabled={!allRowsComplete() || getTotalScore() !== 120}
                className={`w-full py-5 rounded-xl font-semibold text-lg transition-all transform ${
                  allRowsComplete() && getTotalScore() === 120
                    ? 'bg-gradient-to-r from-green-500 to-emerald-600 text-white hover:from-green-600 hover:to-emerald-700 shadow-lg hover:shadow-xl hover:scale-[1.02] active:scale-[0.98]'
                    : 'bg-gray-200 text-gray-400 cursor-not-allowed'
                }`}
              >
                {allRowsComplete() && getTotalScore() === 120
                  ? 'View Results →'
                  : 'Complete All Questions'
                }
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (currentScreen === 'results') {
    const totals = calculateResults();
    const primaryTypes = getPrimaryTypes();
    const labels = ['X', 'T', 'C', 'S'];
    const fullLabels = ['Creator', 'Advancer', 'Executor', 'Refiner'];
    const descriptions = [
      'You are a big-picture thinker who generates new ideas and sees possibilities others miss. You thrive on innovation and love exploring uncharted territory. Your greatest contribution to any team is the ability to envision what could be.',
      'You are an energetic champion who moves ideas forward and rallies others around a vision. You bring momentum, enthusiasm, and social energy to any group. Your greatest contribution is turning possibility into motion.',
      'You are a dependable implementer who makes things happen. You value proven methods, steady progress, and getting the job done right. Your greatest contribution is turning plans into reality with consistency and follow-through.',
      'You are a systematic thinker who ensures quality and precision. You analyze carefully, improve existing processes, and raise the standard of everything you touch. Your greatest contribution is making good things even better.'
    ];
    const colors = [
      'from-orange-500 to-red-600',
      'from-pink-500 to-rose-600',
      'from-blue-500 to-cyan-600',
      'from-green-500 to-emerald-600'
    ];
    const bgColors = ['bg-orange-500', 'bg-pink-500', 'bg-blue-500', 'bg-green-500'];
    const maxScore = Math.max(...totals);

    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 p-4 font-sans">
        <style>{`
          @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
          * { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
        `}</style>
        <div className="max-w-2xl mx-auto pt-12 pb-8">
          <div className="bg-white rounded-3xl shadow-2xl overflow-hidden backdrop-blur-xl bg-opacity-95">
            <div className="p-8 md:p-12">
              <div className="text-center mb-8">
                <p className="text-sm font-semibold text-gray-500 tracking-wide uppercase mb-3">
                  Your Results
                </p>
                <h1 className="text-5xl md:text-6xl font-bold text-gray-900 mb-4 tracking-tight">
                  {primaryTypes.join(' / ')}
                </h1>
                <p className="text-xl text-gray-600 font-medium">
                  {primaryTypes.map(type => fullLabels[labels.indexOf(type)]).join(' / ')}
                </p>
                {scenario && (
                  <p className="text-sm text-gray-500 mt-3 bg-gray-50 inline-block px-4 py-2 rounded-full">
                    {scenario}
                  </p>
                )}
              </div>

              <div className="space-y-5 mb-10">
                {labels.map((label, idx) => (
                  <div key={label} className="group">
                    <div className="flex justify-between mb-2">
                      <span className="font-semibold text-gray-900 text-sm tracking-wide flex items-center gap-2">
                        <span className={`w-2 h-2 rounded-full ${bgColors[idx]}`}></span>
                        {label} — {fullLabels[idx]}
                      </span>
                      <span className="font-bold text-gray-900 text-lg">{totals[idx]}</span>
                    </div>
                    <div className="h-12 bg-gray-100 rounded-2xl overflow-hidden shadow-inner">
                      <div 
                        className={`h-full bg-gradient-to-r ${colors[idx]} transition-all duration-700 ease-out flex items-center justify-end pr-4 group-hover:shadow-lg`}
                        style={{ width: `${(totals[idx] / 48) * 100}%` }}
                      >
                        {totals[idx] === maxScore && (
                          <span className="text-white text-xs font-bold bg-white/20 px-2 py-1 rounded-full backdrop-blur-sm">
                            PRIMARY
                          </span>
                        )}
                      </div>
                    </div>
                    {totals[idx] === maxScore && (
                      <p className="text-sm text-gray-600 mt-2 leading-relaxed">{descriptions[idx]}</p>
                    )}
                  </div>
                ))}
              </div>

              <div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-2xl p-6 mb-8 border border-gray-200">
                <h3 className="font-semibold text-gray-900 mb-4 text-sm tracking-wide uppercase">
                  Score Breakdown
                </h3>
                <div className="grid grid-cols-2 gap-4">
                  {labels.map((label, idx) => (
                    <div key={label} className="bg-white rounded-xl p-4 shadow-sm">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <div className={`w-3 h-3 rounded-full ${bgColors[idx]}`}></div>
                          <span className="text-gray-600 font-medium text-sm">{label}</span>
                        </div>
                        <span className="font-bold text-gray-900 text-xl">{totals[idx]}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <button
                onClick={() => {
                  setCurrentScreen('intro');
                  setRankings(Array(12).fill(null).map(() => [null, null, null, null]));
                  setScenario('');
                }}
                className="w-full bg-gradient-to-r from-gray-700 to-gray-800 text-white py-5 rounded-xl font-semibold text-lg hover:from-gray-800 hover:to-gray-900 transition-all shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98] flex items-center justify-center gap-2"
              >
                <RotateCcw size={20} strokeWidth={2.5} />
                Take Again
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }
};

export default CareAssessment;

Contact Us

Interested in working together? Fill out some info and we will be in touch shortly. We can’t wait to hear from you!